HashMap的源码相对于ArrayList和LinkedList难度提升的不是一点点,因为它的底层数据结构牵扯到了数组、链表、红黑树,源码阅读难度较大,一遍看不懂很正常,对于那些对红黑树都不懂的人,阅读起来更是难上加上。
1、总览
HashMap:它根据键的hashCode值存储数据,大多数情况下可以直接定位到它的值,因而具有很快的访问速度,但遍历顺序却是不确定的。 HashMap最多只允许一条记录的键为null,允许多条记录的值为null。HashMap非线程安全,即任一时刻可以有多个线程同时写HashMap,可能会导致数据的不一致。如果需要满足线程安全,可以用 Collections的synchronizedMap方法使HashMap具有线程安全的能力,或者使用ConcurrentHashMap
2、源码分析
//
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
//
static final int hash(Object key) {
int h;
// h = key.hashCode() 为第一步 取hashCode值
// h ^ (h >>> 16) 为第二步 高位参与运算 高16位异或低16位
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
//
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab;
//记录通过(n - 1) & hash定位到的Hash桶上的元素
Node<K,V> p;
int n, i;
//如果当前table为null或者长度为0,则触发resize进行扩容
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//根据键值key计算hash值与(数组长度-1)进行&运算得到插入的数组索引i,
//如果table[i]==null,直接新建节点添加
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
//判断table[i]的首个元素是否和key一样,如果相同(hashCode以及equals)直接覆盖value
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//判断table[i] 是否为treeNode,即table[i] 是否是红黑树,如果是红黑树,则直接在树中插入键值对
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
//遍历table[i],判断链表长度是否大于8,大于8的话把链表转换为红黑树,
//在红黑树中执行插入操作,否则进行链表的插入操作;
//遍历过程中若发现key已经存在直接覆盖value即可
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
//链接最后一个元素
p.next = newNode(hash, key, value, null);
//当binCount为7时,此时链表长度应该是9了,即当链表长度为8,链接第九个元素后,调用treeifyBin方法,注意
//treeifyBin不一定会把链表转红黑树,如果当前数组长度小于64,会优先resize进行扩容
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//遍历过程中若发现key已经存在直接覆盖value
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;
}
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
//如果当前数组长度小于64,会优先resize进行扩容
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();
else if ((e = tab[index = (n - 1) & hash]) != null) {
TreeNode<K,V> hd = null, tl = null;
do {
TreeNode<K,V> p = replacementTreeNode(e, null);
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);
}
}
3、
4、
参考:
https://zhuanlan.zhihu.com/p/21673805
https://www.bbsmax.com/A/o75N3WbPdW/