hashMap底层实现原理以及源码说明(超级详细版)
大家在面试的时候,经常会碰到关于hashmap的面试题,没了解的同仁,可能会一脸懵,面试官为什么那么喜欢问hashmap相关的东西呢,是因为HashMap里面涉及了很多的知识点,可以比较全面考察面试者的基本功,接下来我说说我对hashmap的个人见解
提示:我会在debug模式下,一点一点的进行hashmap的源码分析
1.这是我测试hashmap代码
2.按下F7,会进入源码中,箭头所指地方是给hashmap赋一个加载因子初始值,初始值为0.75;说明:DEFAULT_LOAD_FACTOR : 负载因子的默认值0.75 表示数据填充的临界值,即数据达到总数据的75%时就开始准备扩容了.
3.这步进入hashmap构造方法中,这步没什么要特殊说明的
4.这里边有个本地方法registerNatives(),说明:调用该方法完成对该类中本地方法进行注册,这个本地方法具体有作用在这里不进行说明,大家有兴趣可以自己搜索以下

5.一直按F7,走到下边一步,这里和大家说一下putval()中的参数:hash(key):这个是获得hash值,下一步我们会讲到;key&value:是你put进来的key&value值;onlyIfAbsent 如果当前位置已存在一个值,是否替换,false是替换,true是不替换;evict 表是否在创建模式,如果为false,则表是在创建模式。

6.进入hash方法,里边有个hashcode方法,这个方法是真正计算hashcode值的地方,说明:对key的hashCode做hash操作,与高16位做异或运算
7.hash计算

8。进入putVal方法,重要步骤进行了文字说明,说明:第4步是jdk1.8对hashmap进行了优化,加入了红黑树,因为之前版本hashmap是数组+链表结构,这个结构会出现当链表过多时,会导致hashmap性能下降很多,加入红黑树以后可以大大改善,具体大家可以进行搜索相关知识
/**
* Implements Map.put and related methods
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent if true, don't change existing value
* @param evict if false, the table is in creation mode.
* @return previous value, or null if none
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
//1.判断map是否为空,如果为空先初始化扩容
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//2.检查table中位置为(n -1 ) & hash 是否为空,如果为空,直接放入(这是放在数组里)
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
//桶中已经存在元素了,也就是说 table中( n -1) & hash这个位置不为空(发生碰撞了)
else {
Node<K,V> e; K k;
//3.如果桶中存在的元素的key和hash都相等,直接覆盖旧value
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//4.判断存放该元素的链表是否转为红黑树,如果为红黑树,直接插入,此时上面3是不成立,hash值不相等,也就是key值不等(hash值是由key算出来的)
else if (p instanceof TreeNode)
//存放在红黑树里
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
//5.第3和第4都不成立,将插入元素存放在链表中
else {
//循环链表,找到链表末尾插入元素
for (int binCount = 0; ; ++binCount) {
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与要插入进来的元素相同,如果相同,跳出循环。
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
// 跟 e = p.next 组成用来遍历链表。
p = e;
}
}
//6.存在key值和hash值相等的,直接覆盖旧value
if (e != null) { // existing mapping for key
//取出e的value
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
//访问后回调
afterNodeAccess(e);
return oldValue;
}
}
//7.将记录修改次数加1,判断是否需要扩容,如果需要就扩容
++modCount;
if (++size > threshold)
resize();
//插入后回调
afterNodeInsertion(evict);
return null;
}
9.这个方法就是第一次put时候,map为空,需要给赋一个初始容量,初始容量为16。说明:面试官会问一个问题,hashmap在什么情况下会进行rehash?rehash是在当超过初始值*加载因子时候会进行hahsmap的扩容
/**
* Initializes or doubles table size. If null, allocates in
* accord with initial capacity target held in field threshold.
* Otherwise, because we are using power-of-two expansion, the
* elements from each bin must either stay at same index, or move
* with a power of two offset in the new table.
*
* @return the table
*/
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
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;
}
10.这一步是真正往hashmap中存值。说明:在查资料的时候很多会说hashmap数组存放单位是Entry,这便是node,这两个是一回事,知识jdk1.8之前是Entry,1.8是node,只是名字不同

==================================补充hashmap的get方法源码===================================
1.进入到hashmap的get方法,里边有hash方法和getNode方法

2.这个获得hash值方法,上边put方法已经讲解过,在这边不再一一进行截图和说明

3.这边才是hahmap中get方法精髓所在
/**
* Implements Map.get and related methods
*
* @param hash hash for key
* @param key the key
* @return the node, or null if none
*/
final Node<K,V> getNode(int hash, Object key) {
//定义变量
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
//查看数据需要满足一下条件
//1)数组不为空
//2)数组长度>0
//3)通过hash计算出该元素在数组中存放位置的索引,而且该索引处数据不为空null
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
//判断该数组索引位置处第一个是否为我们要找的元素 判断条件需要满足hash 和 key 相同
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
//如果第一个就是我们要找的,直接返回即可
return first;
//如果第一个不是,我们需要循环遍历,然后找数据
if ((e = first.next) != null) {
//如果第1个的元素是红黑树类型的节点
if (first instanceof TreeNode)
//那我们需要调用红黑树的方法查找节点
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
//如果不是,则该为链表,需要遍历查找
do {
//循环判断下一个节点的hash和key是否相同
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
//更新e为下一个
} while ((e = e.next) != null);
}
}
return null;
}
源码分析到现在已经基本完成,本人也是在一点一点学习,不足之处,望指出,共同学习,共同进步

浙公网安备 33010602011771号