作为一个开发者,查看源码是一件非常值得去做的事情,因为只有去查看源码我们才会了解底层的实现,才有看到设计者优秀的设计思路和理念,当以后自己再设计某些东西时,可以借鉴参考思路。(例如:JDK的集合、Spring、Mybatis等)
1、HashMap的概述
HashMap是我们常用的一个集合之一,底层是由数组+单向链表实现的,与HashTable不同之处是线程不安全、允许null 作为key和value,在多线程的情况下会发生死链(链表进入环状,进入死链的场景),所以在高并发的场景下,我们可以采ConcurrentHashMap 来兼顾性能和安全(PS:它是jdk1.5时引入的,基于分段锁技术,来兼顾性能和安全)
2、HashMap的结构
jdk1.8之前 每个key和value 叫做Entry, 1.8后改为了Node
HashMap数组每一个元素的初始值都是Null,默认大小为16,最大为2的30次方
/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/**
* The maximum capacity, used if a higher value is implicitly specified
* by either of the constructors with arguments.
* MUST be a power of two <= 1<<30.
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
当我们调用put(“apple”,12)时,它会调用哈希算法生成一个index放入数组的某个位置
/**
* 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);
}
我们知道HashMap的默认大小是16,那数组的下标就是0-15,我们很容易想到 index=hash(key)%15 ,但是底层为了提高运算效率,采用的是位运算
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
当生成index相同时,那会在那个地方向后插入一个链表
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;
在上面声明HashMap初始化大小时,一段注释 The default initial capacity - MUST be a power of two. 有没有会产生一个这样的一个疑问?为啥默认长度是16 或者是2的幂?那我们先来看下index的生成过程,从前面我们知道 index = HashCode(Key) & (Length - 1)
下面我们以值为“book”的Key来演示整个过程:
1.计算book的hashcode,结果为十进制的3029737,二进制的101110001110101110 1001。
2.HashMap长度是默认的16,计算Length-1的结果为十进制的15,二进制的1111
3.把以上两个结果做与运算,101110001110101110 1001 & 1111 = 1001,十进制是9,所以 index=9
从上述的结果 可以说,Hash算法最终得到的index结果,完全取决于Key的Hashcode值的最后几位
假设HashMap的长度是10,重复刚才的运算步骤:
再来一个新的HashCode,来看看结果:
还来一个新的HashCode试试,看看结果
上面的三个HashCode倒数第二第三位从0变成了1,但是运算的结果都是1001。也就是说,当HashMap长度为10的时候,有些index结果的出现几率会更大,而有些index结果永远不会出现(比如0111)!
这样将会导致某些链表越来越长,从而使得链表的缺点暴露越来越明显,查询起来越来越慢,也不符合hash算法均匀分布的原则
反观长度16或者其他2的幂,Length-1的值是所有二进制位全为1,这种情况下,index的结果等同于HashCode后几位的值。
为了HashCode尽量均匀系统为HashCode进行了异或运算
/**
* 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);
}
到这有人就会想到,那HashMap的数组啥时候扩大呢?它有着一个自己的扩容因子0.75,也就是说当数组用完12个时,就会自动扩容
/**
* The load factor used when none specified in constructor.
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
当我们调用put方法时,第一个就是判断大小,是否该扩容了,在resize()方法中进行扩容,把原来数组上数据复制到新的数组中重新分布
/**
* The table, initialized on first use, and resized as
* necessary. When allocated, length is always a power of two.
* (We also tolerate length zero in some operations to allow
* bootstrapping mechanics that are currently not needed.)
*/
transient Node<K,V>[] table;
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
/**
* 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;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
JDK1.8后 HashMap中增加了两个阀值,当单个链表中的元素达到8个时,会改用红黑树结构来存储数据,当树结构的节点小于6时,又会转成链表结构
/**
* The bin count threshold for using a tree rather than list for a
* bin. Bins are converted to trees when adding an element to a
* bin with at least this many nodes. The value must be greater
* than 2 and should be at least 8 to mesh with assumptions in
* tree removal about conversion back to plain bins upon
* shrinkage.
*/
static final int TREEIFY_THRESHOLD = 8;
/**
* The bin count threshold for untreeifying a (split) bin during a
* resize operation. Should be less than TREEIFY_THRESHOLD, and at
* most 6 to mesh with shrinkage detection under removal.
*/
static final int UNTREEIFY_THRESHOLD = 6;