本源码为JDK8版本
HashMap的源码较简单,这里主要从源码解析下一些基本操作的原理。
静态常量
首先给出几个基本常量的值
/**
* The default initial capacity - MUST be a power of two
* 默认初始化容量为16(注意容量必须是2的次方)
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/**
* The maximum capacity, used if a higher value is implicitly specified
* by either of the constructors with arguments.
* MUST be a power of two <= 1<<30.
* 最大容量为2的30次方,指定容量大于此容量时,会等效于最大容量。
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* The load factor used when none specified in constructor.
* 默认的装载因子,当size > loadFactor * capacity时会进行扩容
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
* The bin count threshold for using a tree rather than list for a
* bin. Bins are converted to trees when adding an element to a
* bin with at least this many nodes. The value must be greater
* than 2 and should be at least 8 to mesh with assumptions in
* tree removal about conversion back to plain bins upon
* shrinkage.
* 当链表的长度>=8,即转为红黑树
*/
static final int TREEIFY_THRESHOLD = 8;
/**
* The bin count threshold for untreeifying a (split) bin during a
* resize operation. Should be less than TREEIFY_THRESHOLD, and at
* most 6 to mesh with shrinkage detection under removal.
* resize时将红黑树转为链表的threshold
*/
static final int UNTREEIFY_THRESHOLD = 6;
/**
* The smallest table capacity for which bins may be treeified.
* (Otherwise the table is resized if too many nodes in a bin.)
* Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts
* between resizing and treeification thresholds.
* 链表转换为红黑树的最小容量(否则链表长度>=threshold时会直接resize)
*/
static final int MIN_TREEIFY_CAPACITY = 64;
基本节点类型
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;//节点hash值
final K key;
V value;
Node<K,V> next;//next指针
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
//省略
}
计算hash值
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
key.hashCode()即为key值原本的hash值,HashMap的hash方法是保持hash code的高16位不变,高16位与低16位做异或操作。注释解释是,因为已经使用红黑树来处理链表大量的碰撞,因此选择这种最cheap的方法来降低系统消耗,同时也对高位进行了操作(否则由于table的限制高位基本不会使用)。
基本变量
//transient在序列化对象时,变量不会序列化
//table数组
transient Node<K,V>[] table;
//缓存的entrySet()
transient Set<Map.Entry<K,V>> entrySet;
//HashMap的size大小
transient int size;
//对HashMap进行结构修改的次数
transient int modCount;
//当前table的最大容量(默认16)
int threshold;
//装载因子(默认0.75)
final float loadFactor;
HashMap初始化时,若未指定initialCapacity, loadFactor,会指定为默认值。
put操作
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
这里传入了key的Hash值,hash方法如上。直接看putVal()方法。
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
//若table为空,则先初始化table
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//(n - 1) & hash 确定下标,若该下标不存在,则指定newNode
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
//判断p与传入的键值对的key、hash是否相同
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//若不同,且为红黑树节点,则在红黑树中插入节点
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
//否则,在链表中进行插入操作(插入后若长度>=8,会转为红黑树)
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
//定位到e即已存在的节点,替换value值
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
//插入后会判断size,决定是否扩容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
put操作可总结如下:
首先判断table是否为null,为null会调用resize()方法进行第一次初始化。
(n - 1) & hash 定位下标,若不存在值,则直接插入。
若下标处已有值,则在链表或红黑树上查找做插入操作,这里链表是尾插法。
插入后modCount、size自增,如果size > threshold,会调用resize()方法进行扩容操作。
注意:
链表插入时,若长度>=8,会将链表转换为红黑树。
get操作
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
通过getNode(int hash, Object key)方法来获得节点
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
通过源码可以看到,就是非常常规的查找操作,不再赘述。
注意:
红黑树查找时间复杂度:O(logn)
链表查找时间复杂度:O(n)
扩容操作
对HashMap进行扩容时,实际上调用的是resize()方法
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
//首先要确定新的threshold
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
//复制操作
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
扩容时,先增大threshold,然后创建newTab,复制原table。
这里注意:
根据(e.hash & oldCap)的结果,
若为0,则下标保持不变,若不为0,则下标+oldCap;(保持相对顺序不变)