前提:我没有写博客的经验,我只是觉得想写就写。没时间加工就不加工,有时间重写就重写。
分析HashMap的put方法,下面贴出jdk1.8中的源码
//在进行put操作时首先调用的这个方法,没什么具体意义
//putVal() :具体存储操作
//hash(key):计算key的hash值
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
//计算方法没啥好解释的(我不会),拿来key的hashCode进行高位运算
//因为普通的hashCode算法非常容易起hash冲突
//取key的hashCode值、高位运算、取模运算
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
/**
* 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) {
//创建数组tab 节点p 数组的长度n 索引i
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
//记录初始化时数组的长度
n = (tab = resize()).length;
//根据key的hash值再次运算出该元素所要存储的位置i,为空则创建新的节点进行存储
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
//重点
Node<K,V> e; K k;
//节点key存在,直接覆盖value
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//如果通过equals判断后不相等,则判断该索引位置存的是链表还是红黑树
//p instanceof TreeNode 属于红黑树,则使用自定义红黑树的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);
//注意二:当链表长度>=8时,转换为红黑树
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;
}
}
//这段是判断是否之前存在值,如果存在则进行返回
//没错!hashMap进行put时是有返回值的,返回旧值!
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
//维护修改次数
++modCount;
//维护map的size以及判断:size超过最大阈值(默认为12)就进行扩容操作
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
白话解析:
1.通过取key的hashCode值、高位运算、取模运算计算之后得到数组中的位置索引i
2.如果该位置已经存在元素,则对key进行equals判断,如果为true,则覆盖value,如果为false,则进一步判断该位置存储的是链表还是红黑树,是链表则为(key,value)生成新的节点,插入到链表尾节点(原因:p.next = newNode(hash, key,value,null))
关于resize()方法,实在遭不住,我的数据结构基础很差,红黑树也只是知道个概念,
我认为看源码,并不是每个方法,每一步都要看懂,根据自己的能力看吧,毕竟其中的具体运算,都是经过日积月累得出来的,没有人带入,一时半会很难懂。
比如我曾想问,为什么当链表长度到8时才转换成红黑树?
得到的答案:
因为红黑树需要进行左旋,右旋操作, 而单链表不需要,
以下都是单链表与红黑树结构对比。
如果元素小于8个,查询成本高,新增成本低
如果元素大于8个,查询成本低,新增成本高
我当这是放屁,我认为8这个值一定是作者通过千百次实验验证的结果,而不是胡乱两句就能概括的,其实这里涉及到了时间复杂度度分析,我又不懂了…
当红黑树节点个数小于 6 时,又会转化成链表
ps:如果你懂,请不要吝啬,可以教教我吗
参考:美团技术团队 Java 8系列之重新认识HashMap