HashMap
java中使用非常之频繁的一种数据接口,面试中也频繁考察的一种数据结构。处于好奇的心态,简单分析一下它的源码。
JDK1.8
本篇博客的基于JDK 1.8版本,其他版本暂时不做分析。
开始
日常使用HashMap,用得比较多的方法就是put/get了,那就从put开始入手:
/**
* Associates the specified value with the specified key in this map.
* If the map previously contained a mapping for the key, the old
* value is replaced.
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
* @return the previous value associated with <tt>key</tt>, or
* <tt>null</tt> if there was no mapping for <tt>key</tt>.
* (A <tt>null</tt> return can also indicate that the map
* previously associated <tt>null</tt> with <tt>key</tt>.)
*/
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
根据注释还是比较好理解的,解释了一下key会与value做关联,如果key已经存在,那么新的value会覆盖掉旧的value,并且返回出来旧的value。另外解释了一下value可以是null,也会被返回出来。再去看一下putVal中的hash(key)方法
/**
* Computes key.hashCode() and spreads (XORs) higher bits of hash
* to lower. Because the table uses power-of-two masking, sets of
* hashes that vary only in bits above the current mask will
* always collide. (Among known examples are sets of Float keys
* holding consecutive whole numbers in small tables.) So we
* apply a transform that spreads the impact of higher bits
* downward. There is a tradeoff between speed, utility, and
* quality of bit-spreading. Because many common sets of hashes
* are already reasonably distributed (so don't benefit from
* spreading), and because we use trees to handle large sets of
* collisions in bins, we just XOR some shifted bits in the
* cheapest possible way to reduce systematic lossage, as well as
* to incorporate impact of the highest bits that would otherwise
* never be used in index calculations because of table bounds.
*/
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
注释中讲得也很明白,主要是避免频繁在一些场景下出现key计算出的hash值仅仅高位变动,低位相同的情况造成的严重碰撞。于是直接把hash值的无符号右移16位(高位0补齐)与原hash值异或,扩大高16位的影响力得出最终的hash值。下面进入putVal()方法:
/**
* 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;
// 这边做了一个判断,可以看出HashMap桶空间的初始化是在put时进行的
// 也就是实例化时并没有创建内部空间,用时再创建,节省空间
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// 下面就是寻址了,(n-1) & hash非常巧妙,也解释了为什么HashMap内部桶个数是2的幂次
// n为2的幂次减去1后的二进制数就都是1了
// 举个例子16的二进制数是10000,减一后为1111(高位补0),hash 32位
// 1111 & hash 后必然是前28位都是0,后4位为真正结果,但是也必然是0-15中的一个数
// 也就对应了16个桶中的一个下标了,非常巧妙
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
// 如果出现碰撞则形成链表,链表超过了8位则转红黑树
// 至于为何是8位其实源码注释里也说明白了
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;
}