揭晓HashMap在什么情况下用数组或单向链表或红黑树来存储数据
首先要知道,HashMap提供了三种用于存储元素的数据结构:数组、单向链表和红黑树。接下来分析HashMap怎么决定用哪种数据结构来存储数据。
先直接上代码,把HashMap存储数据的过程捋顺一下:
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
可知调用到了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; -->Node是单向链表节点类
if ((tab = table) == null || (n = tab.length) == 0)--->得到此HashMap的数组长度为n
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)--->key的hash值对(n-1)取余,得到该数组应该存储该key的位置i,此位置上的元素是p
tab[i] = newNode(hash, key, value, null);-->p为空,则new出一个节点存入数组
else {-->p不为空
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;-->如果key的hash值恰好等于p的hash值,且key和p.key相等,则p赋值给e
else if (p instanceof TreeNode)-->如果p是树节点
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {-->如果p不是树节点,即p是链表节点
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);-->如果p所在的单向列表长度已经大于等于7了,调用此方法
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
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;
}
可知如果用于存储当前新存入元素的链表的大小已经大于等于7的情况下,那么就会调用“树化”treeifyBin方法,接下来看该方法里的流程:
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();
else if ((e = tab[index = (n - 1) & hash]) != null) {-->可知e是数组里的元素,即用于存放当前新put的元素的链表的头结点
TreeNode<K,V> hd = null, tl = null;
do {
TreeNode<K,V> p = replacementTreeNode(e, null);-->e转成红黑树节点p
if (tl == null)
hd = p;
else {
p.prev = tl;
tl.next = p; -->把单向链表转成双向链表,为成为红黑树作准备
}
tl = p;
} while ((e = e.next) != null);
if ((tab[index] = hd) != null)
hd.treeify(tab);-->构建红黑树
}
}
可知,HashMap的put中想要存入一个元素,会首先根据该元素的hash值找到它应该在数组中存入的位置,如果该位置没有元素,就存入数组中;如果有数据,那么以该位置为头结点的单向链表的长度如果小于7,则存入该单项链表中,否则将该单项链表转为红黑树存入该元素