一、基础知识
在Java7中,HashMap采用的是数组+链表的形式存储的,(默认bucket数目16,负载因子0.75),参见笔者上一篇文章:Java7 中 HashMap 的实现原理与底层数据结构。
hashmap最关键的操作就是hash的逻辑,即根据把各种给了键值对的节点node,对应到数组中的逻辑,也就是确定哈希桶数组索引位置,然后才能谈冲突后的存储和处理方式。本文要详细解析的就是hash的这个映射过程。
关于hashmap的基础知识部分,在这里就不解释了,给出1.7及之前的hashmap内部存储的图解:
JDK1.7源码提要
int hash = hash(key);
int i = indexFor(hash, table.length);
- 求hash值
- 根据hash值和数组的长度length定位到数组里的具体位置。
1.1 计算 hash 值
final int hash(Object k) {
int h = hashSeed;
if (0 != h && k instanceof String) {
return sun.misc.Hashing.stringHash32((String) k);
}
h ^= k.hashCode();
// 高低位扰动计算
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
先不用管具体实现,只需要知道它是通过对给的node中的key(键)调用每个Object都有的hashCode()方法得到一个值,然后做了一些处理,就给出了这里的hash值。
1.2 计算索引
static int indexFor(int h, int length) {
return h & (length-1);
}
把得到的hash值,对应到数组那个长度里。
这一计算方式有诸多优点:
- 首先这是个位运算,速度快。
- 当 length 为2的次幂时,保证 length-1 的二进制除最高位为0,其余位都为1,减少哈希冲突;
- 同时满足 h & (length-1) = hash % length。
二、JDK1.8的改动
2.1 存储结构改进
Java8采用了数组+链表+红黑树的存储结构。对于 JDK1.8 之后的 HashMap 底层在解决哈希冲突的时候,就不单单是使用数组加上单链表的组合了,因为当处理如果 hash 值冲突较多的情况下,链表的长度就会越来越长,此时通过单链表来寻找对应 Key 对应的 Value 的时候就会使得时间复杂度达到 O(n),因此在 JDK1.8 之后,在链表新增节点导致链表长度超过 TREEIFY_THRESHOLD = 8 的时候,就会在添加元素的同时将原来的单链表转化为红黑树。
红黑树是一种易于增删改查的二叉树,他对与数据的查询的时间复杂度是 O(logn) 级别,所以利用红黑树的特点就可以更高效的对 HashMap 中的元素进行操作。
而在hash方面,首先,在高位扰动方面,只是简单的h = h ^ (h >>> 16),没有再做那么多的扰动,就得到了hash值。
我自己的理解是,由于用红黑树优化了冲突很多,链很长的情况,所以没必要做那么多的高低位扰动了。有了冲突也可以处理。
2.2 头插改为尾插
其次,添加元素的时候从头插改为尾插,解决了多线程可能导致的”环形链表“问题。
分析链表插入的位置,重点是分析HashMap的put方法。
public V put(K key, V value) {
if (key == null)
return putForNullKey(value);
int hash = hash(key.hashCode());
int i = indexFor(hash, table.length);
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
//如果发现key已经在链表中存在,则修改并返回旧的值
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
//如果遍历链表没发现这个key,则会调用以下代码
modCount++;
addEntry(hash, key, value, i);
return null;
}
阅读源码发现,如果遍历链表都没法发现相应的key值的话,则会调用addEntry方法在链表添加一个Entry,重点就在与addEntry方法是如何插入链表的,addEntry方法源码如下:
void addEntry(int hash, K key, V value, int bucketIndex) {
Entry<K,V> e = table[bucketIndex];
table[bucketIndex] = new Entry<K,V>(hash, key, value, e);
if (size++ >= threshold)
resize(2 * table.length);
}
这里构造了一个新的Entry对象(构造方法的最后一个参数传入了当前的Entry链表),然后直接用这个新的Entry对象取代了旧的Entry链表,可以猜测这应该是头插法,为了进一步确认这个想法,我们再看一下Entry的构造方法:
Entry( int h, K k, V v, Entry<K,V> n) {
value = v;
next = n;
key = k;
hash = h;
}
从构造方法中的nexrt=n可以看出确实是把原本的链表直接链在了新建的Entry对象的后边,可以断定是插入头部。
jdk1.8
put方法的代码如下:
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
继续进入putVal方法(先不要着急去读它):
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
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 {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
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;
}
}
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;
}
在jdk1.8中当链表长度大于8是会被转化成红黑树,所以源码看起来比jdk1.6要复杂不少,大量的if-else判断是为了处理红黑树的情况的,与链表插入相关的核心代码只有如下几行:
for (int binCount = 0; ; ++binCount) {
//e是p的下一个节点
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;
}
//如果key在链表中已经存在,则退出循环
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
//如果key在链表中已经存在,则修改其原先的key值,并且返回老的值
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
代码我一行行加了注释,其中链表插入的代码是:
//e是p的下一个节点
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;
}
从这段代码中可以很显然地看出当到达链表尾部(即p是链表的最后一个节点)时,e被赋为null,会进入这个分支代码,然后会用newNode方法建立一个新的节点插入尾部。