hashMap的底层原理实现★★★
JDK1.7 hashMap底层数据结构是数组+链表;JDK1.8之后底层数据结构是数组+链表+红黑树;
JDK1.7 hashMap执行put方法时,会先声明一个长度为16的数组,计算key的hash值,再对hash值进行数组长度取模的二次hash,得到对应的数组下标;判断数组下标对应的元素是否为空,如果为空,则直接将对应的value放在该数组下标所对应的位置上,如果不为空(出现hash冲突),首先判断数组中原来的key和当前key是否是相等的,如果是相等的,直接覆盖掉原有的key所对应的数据;如果key不相等,则遍历链表,判断有无key和当前key相等,如果相等则直接覆盖,不相等则插入链表尾部;
JDK1.8 hashMap 执行put方法和上面流程基本一致,但是多了一步判断链表长度是否 >=8 同时数组长度是否大于等于64 ,如果大于,则进行红黑树的转换,在红黑树中进行元素的插入;
JDK1.8之后的HashMap的put方法的源码解析:
// table就是 hashMap 中底层数据结构中的数组;
transient Node<K,V>[] table;
// 数组初始大小 2^4次方 =16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
// 加载因子 通过数组长度和数组大小,就可以计算扩容阈值,如果数组长度>=扩容阈值,就会进行数组的扩容
static final float DEFAULT_LOAD_FACTOR = 0.75f;
// hashMap中 Node 静态内部类的定义
static class Node<K,V> implements Map.Entry<K,V> {
final int hash; // hash值
final K key; // 键值
V value; // value值
Node<K,V> next; // 下一个 数组中存放的是链表元素
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
// hashMap源码中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) {
// tab就是hashMap底层数据结构中的数组; Node是该数组中存放的元素
Node<K,V>[] tab; Node<K,V> p; int n, i;
// 如果数组长度为空或者为0,就调用resize();第一次调用resize() 由于table为null,所以会返回一个长度为16的数组;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// 如果传参而来的hash值,通过数组长度的取模进行二次hash得到的数组下标所对应的元素为null,直接在该数组位置添加newNode即可 因为数组中存放的是链表节点;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
// 当前key的hash值和原来数组中存放的hash值相同 (出现哈希冲突),且当前key和原来key的值也相同,那么就会直接覆盖掉原来节点
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);
else {
// 遍历链表,利用binCount来记录链表长度
for (int binCount = 0; ; ++binCount) {
// 如果遍历到链表的尾部都没有和当前节点hash值相同,且key也相同的点,那就直接在尾部插入新节点
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
// 如果链表长度是否>=8
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
// 转换为红黑树
treeifyBin(tab, hash);
break;
}
// 如果在遍历链表时发现存在一个hash冲突,且链表中存在节点的key和当前key相同,那就直接覆盖
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;
// 如果当前数组长度+1之后的大小 > 扩容阈值
if (++size > threshold)
// 就触发扩容
resize();
afterNodeInsertion(evict);
return null;
}