对源码的分析大部分写在代码的注释里。
构造函数
public HashMap() {
// 只设置了0.75f负载因子
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
// 根据初始化容量计算扩容阈值
this.threshold = tableSizeFor(initialCapacity);
}
// 返回值为2的n次幂
static final int tableSizeFor(int cap) {
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
// evict只有在初始化时才为false,其他时候为true。
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
int s = m.size();
if (s > 0) {
if (table == null) { // pre-size
float ft = ((float)s / loadFactor) + 1.0F;
int t = ((ft < (float)MAXIMUM_CAPACITY) ?
(int)ft : MAXIMUM_CAPACITY);
if (t > threshold)
threshold = tableSizeFor(t);
}
else if (s > threshold)
// 大于阈值,扩容
resize();
for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
K key = e.getKey();
V value = e.getValue();
putVal(hash(key), key, value, false, evict);
}
}
}
Node和TreeNode的关系
每个node可以是一条链表,整个HashMap有多个node,即数组+链表,之后可以树化
TreeNode和Node的关系:
class TreeNode<K,V> extends LinkedHashMap.Entry<K,V>
class LinkedHashMap.Entry<K,V> extends HashMap.Node<K,V>
class HashMap.Node<K,V> implements Map.Entry<K,V>
resize()方法
final HashMap.Node<K,V>[] resize() {
// 保存全部结点
HashMap.Node<K,V>[] oldTab = table;
// 旧容量即可有多少个Node
int oldCap = (oldTab == null) ? 0 : oldTab.length;
// 旧阈值即容量达到该值时需要扩容
int oldThr = threshold;
// 先初始化一个新容量和新阈值
int newCap, newThr = 0;
// 旧容量大于0时
if (oldCap > 0) {
// oldCap >= 2的30次方,阈值设为2的31次方-1,扩容结束
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
// 新阈值=旧阈值*2
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
// oldCap<=0,oldThr>0,新容量=旧阈值
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
// oldCap<=0,oldThr<=0;
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;
// 判断是使用新阈值还是Integer.MAX_VALUE
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
// 将新阈值设置到HashMap里
threshold = newThr;
// 新建一个Node数组,长度为newCap
@SuppressWarnings({"rawtypes","unchecked"})
HashMap.Node<K,V>[] newTab = (HashMap.Node<K,V>[])new HashMap.Node[newCap];
// 将HashMap的Node数组引用指向新数组
table = newTab;
// 如果旧Node数组不为空,复制其数据到新数组
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
HashMap.Node<K,V> e;
// 把旧数组的Node赋给e,然后判断e是否为空,不为空继续操作
if ((e = oldTab[j]) != null) {
// 把旧数组的Node置为空
oldTab[j] = null;
// e没有下一个结点时(即某个Node没有链时)
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
// e是树结点时(某个Node已树化时)
else if (e instanceof HashMap.TreeNode)
// 拆分树结点
((HashMap.TreeNode<K,V>)e).split(this, newTab, j, oldCap);
// e不为空也不是树结点时(某个Node还是链表时)
else { // preserve order
// 拆分链表结点
HashMap.Node<K,V> loHead = null, loTail = null;
HashMap.Node<K,V> hiHead = null, hiTail = null;
HashMap.Node<K,V> next;
do {
// next指向e的下个结点
next = e.next;
// 数组下标的计算方法为(cap - 1) & hash
// 原数组下标为(oldCap - 1) & hash(key)
// e.hash就是hash(key)得来的
// 通过判断(e.hash & oldCap) == 0,
// 因为oldCap是2的n次方,例如:10000,所以上面的表达式其实就是判断e的key进行hash之后的值在对应oldCap某位上是否为0,以此为依据将原来的链表分成两条链表,分别是lohead->loTail,liHead->liTail
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);
// loTail如果为空意味着没有以loHead开头的链表
if (loTail != null) {
loTail.next = null;
// loHead链表放置在新数组的索引:旧索引
newTab[j] = loHead;
}
// hiTail如果为空意味着没有以hiHead开头的链表
if (hiTail != null) {
hiTail.next = null;
// hiHead链表放置在新数组的索引:旧索引+旧容量
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
put()方法
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
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为空或者长度为0时,扩容
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// 通过(n - 1) & hash计算出索引,判断该索引处是否为空,为空就插入
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
// 该索引处不为空,把新Node接到链表或者树的后面去
else {
Node<K,V> e; K k;
// 如果新插入Node与数组的p结点的key的hash值相同并且key的内容相同,那么把原Node赋给e,下面会对该Node的value进行覆盖
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
// 如果数组里的p结点时树结点,那么执行putTreeVal
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
// 将新结点插到链表末尾
else {
for (int binCount = 0; ; ++binCount) {
// 到达末尾,插入新结点
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
// 如果binCount>=8-1时,即bin中的结点超过8个时执行treeifyBin,判断是否需要树化
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;
}
}
// 存在相同的Node,覆盖掉原来的Node,返回原来的Node的value
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
树化条件
在putVal()方法里:
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
在treetreeifyBin()方法里:
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();
由此可见,如果要树化,需要bin里的Node个数达到9,并且Node数组长度 >= MIN_TREEIFY_CAPACITY。
没有达到以上条件只会进行扩容。
红黑树退化成链表
树化解除的方法为untreeify()。在split()和removeTreeNode()中都有出现,两个方法中解除树化的条件不一样。
split()中,如果树的大小不足6,就会解除树化,退化为链表。
if (loHead != null) {
if (lc <= UNTREEIFY_THRESHOLD)
tab[index] = loHead.untreeify(map);
else {
tab[index] = loHead;
if (hiHead != null) // (else is already treeified)
loHead.treeify(tab);
}
}
if (hiHead != null) {
if (hc <= UNTREEIFY_THRESHOLD)
tab[index + bit] = hiHead.untreeify(map);
else {
tab[index + bit] = hiHead;
if (loHead != null)
hiHead.treeify(tab);
}
}
removeTreeNode()中,树化解除的条件有多种可能:
-
根结点为空
-
根结点的右子树为空
-
根结点的左子树为空
-
根结点的左子树的左子树为空
if (root == null
|| (movable
&& (root.right == null
|| (rl = root.left) == null
|| rl.left == null))) {
tab[index] = first.untreeify(map); // too small
return;
}