使用的jdk是1.8
在看源码前,你需要看下hashmap的数据结构的图,这样能帮助你理解分析源码:
关于hashmap槽位算法(数组下标)的思考(也叫为什么hashmap的容量为什么是2的倍速):
其实在1.8的源码里可以看见计算槽位的公式很简单: (n - 1) & hash 此公式可以理解为 hash % ( n-1)计算除以长度得到的下标即是数组下标了. 不过是用位运算效率高,所以采用这种方式
为什么要求n是2的倍数呢?我当时也很好奇,知道后来看到几篇博客,理解到了其中的原由. 2的倍数减1的二进制位后面都是111111 比如15的2进制是0000 1111, 如果某个key的hash是0000 1100 那么两者与运算的结果是
n-1 0000 1111
hash 0000 1100
结果: 0000 1100
你会发现这结果是由hash决定的, 如果hash是散列的, 那么计算出来的槽位下标也是分散的.
put方法解析
介绍一下hashmap的put方法,从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;
// transient Node<K,V>[] table;初始化
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// (n - 1) & hash 计算数组下标的方法快看腻了, 很多博客都写出来
//如果计算到下标的槽没有值(即没有发生哈希冲突),那就直接new Node放到当前槽位
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
// 如果进入这个else 就是发生哈希冲突
else {
Node<K,V> e; K k;
// 计算哈希冲突的处理方法1
// 当前槽位的链表的第一个元素(下面用p表示)和待input的node的hash是否一致,key是否一致,如果一致(即插入相同的key),跳转到47行 的 if (e != null){覆盖操作,或者不覆盖操作}
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e