HashMap的扩容机制---resize()
面试的时候闻到了Hashmap的扩容机制,之前只看到了Hasmap的实现机制,补一下基础知识,讲的非常好
原文链接:
http://www.iteye.com/topic/539465
Hashmap是一种非常常用的、应用广泛的数据类型,最近研究到相关的内容,就正好复习一下。网上关于hashmap的文章很多,但到底是自己学习的总结,就发出来跟大家一起分享,一起讨论。
1、hashmap的数据结构
要知道hashmap是什么,首先要搞清楚它的数据结构,在java编程语言中,最基本的结构就是两种,一个是数组,另外一个是模拟指针(引用),所有的数据结构都可以用这两个基本结构来构造的,hashmap也不例外。Hashmap实际上是一个数组和链表的结合体(在数据结构中,一般称之为“链表散列“),请看下图(横排表示数组,纵排表示数组元素【实际上是一个链表】)。
从图中我们可以看到一个hashmap就是一个数组结构,当新建一个hashmap的时候,就会初始化一个数组。我们来看看java代码:
Java代码 Java里的数组是无法自动扩容的,方法是使用一个新的数组代替已有的容量小的数组,就像我们用一个小桶装水,如果想装更多的水,就得换大水桶。
我们分析下resize的源码,鉴于JDK1.8融入了红黑树,较复杂,为了便于理解我们仍然使用JDK1.7的代码,好理解一些,本质上区别不大,具体区别后文再说。
- void resize(int newCapacity) { //传入新的容量
- Entry[] oldTable = table; //引用扩容前的Entry数组
- int oldCapacity = oldTable.length;
- if (oldCapacity == MAXIMUM_CAPACITY) { //扩容前的数组大小如果已经达到最大(2^30)了
- threshold = Integer.MAX_VALUE; //修改阈值为int的最大值(2^31-1),这样以后就不会扩容了
- return;
- }
- Entry[] newTable = new Entry[newCapacity]; //初始化一个新的Entry数组
- transfer(newTable); //!!将数据转移到新的Entry数组里
- table = newTable; //HashMap的table属性引用新的Entry数组
- threshold = (int) (newCapacity * loadFactor);//修改阈值
- }
- void transfer(Entry[] newTable) {
- Entry[] src = table; //src引用了旧的Entry数组
- int newCapacity = newTable.length;
- for (int j = 0; j < src.length; j++) { //遍历旧的Entry数组
- Entry
e = src[j]; //取得旧Entry数组的每个元素 - if (e != null) {
- src[j] = null;//释放旧Entry数组的对象引用(for循环后,旧的Entry数组不再引用任何对象)
- do {
- Entry
next = e.next; - int i = indexFor(e.hash, newCapacity); //!!重新计算每个元素在数组中的位置
- e.next = newTable[i]; //标记[1]
- newTable[i] = e; //将元素放在数组上
- e = next; //访问下一个Entry链上的元素
- } while (e != null);
- }
- }
- }
- static int indexFor(int h, int length) {
- return h & (length - 1);
- }
newTable[i]的引用赋给了e.next,也就是使用了单链表的头插入方式,同一位置上新元素总会被放在链表的头部位置;这样先放在一个索引上的元素终会被放到Entry链的尾部(如果发生了hash冲突的话),这一点和Jdk1.8有区别,下文详解。在旧数组中同一条Entry链上的元素,通过重新计算索引位置后,有可能被放到了新数组的不同位置上。
下面举个例子说明下扩容过程。
这句话是重点----hash(){return key % table.length;}方法,就是翻译下面的一行解释:
假设了我们的hash算法就是简单的用key mod 一下表的大小(也就是数组的长度)。
其中的哈希桶数组table的size=2, 所以key = 3、7、5,put顺序依次为 5、7、3。在mod 2以后都冲突在table[1]这里了。这里假设负载因子 loadFactor=1,即当键值对的实际大小size 大于 table的实际大小时进行扩容。接下来的三个步骤是哈希桶数组 resize成4,然后所有的Node重新rehash的过程。

下面我们讲解下JDK1.8做了哪些优化。经过观测可以发现,我们使用的是2次幂的扩展(指长度扩为原来2倍),所以,
经过rehash之后,元素的位置要么是在原位置,要么是在原位置再移动2次幂的位置。对应的就是下方的resize的注释。
[java] view plain copy- /**
- * Initializes or doubles table size. If null, allocates in
- * accord with initial capacity target held in field threshold.
- * Otherwise, because we are using power-of-two expansion, the
- * elements from each bin must either stay at same index, or move
- * with a power of two offset in the new table.
- *
- * @return the table
- */
- final Node
[] resize() {
看下图可以明白这句话的意思,n为table的长度,图(a)表示扩容前的key1和key2两种key确定索引位置的示例,图(b)表示扩容后key1和key2两种key确定索引位置的示例,其中hash1是key1对应的哈希与高位运算结果。

元素在重新计算hash之后,因为n变为2倍,那么n-1的mask范围在高位多1bit(红色),因此新的index就会发生这样的变化:

因此,我们在扩充HashMap的时候,不需要像JDK1.7的实现那样重新计算hash,只需要看看原来的hash值新增的那个bit是1还是0就好了,是0的话索引没变,是1的话索引变成“原索引+oldCap”,可以看看下图为16扩充为32的resize示意图:

这个设计确实非常的巧妙,既省去了重新计算hash值的时间,而且同时,由于新增的1bit是0还是1可以认为是随机的,因此resize的过程,均匀的把之前的冲突的节点分散到新的bucket了。这一块就是JDK1.8新增的优化点。有一点注意区别,JDK1.7中rehash的时候,旧链表迁移新链表的时候,如果在新表的数组索引位置相同,则链表元素会倒置,但是从上图可以看出,JDK1.8不会倒置。有兴趣的同学可以研究下JDK1.8的resize源码,写的很赞,如下:
-
1 final Node
[] resize() { -
2 Node
[] oldTab = table; - 3 int oldCap = (oldTab == null) ? 0 : oldTab.length;
- 4 int oldThr = threshold;
- 5 int newCap, newThr = 0;
- 6 if (oldCap > 0) {
- 7 // 超过最大值就不再扩充了,就只好随你碰撞去吧
- 8 if (oldCap >= MAXIMUM_CAPACITY) {
- 9 threshold = Integer.MAX_VALUE;
- 10 return oldTab;
- 11 }
- 12 // 没超过最大值,就扩充为原来的2倍
- 13 else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
- 14 oldCap >= DEFAULT_INITIAL_CAPACITY)
- 15 newThr = oldThr << 1; // double threshold
- 16 }
- 17 else if (oldThr > 0) // initial capacity was placed in threshold
- 18 newCap = oldThr;
- 19 else { // zero initial threshold signifies using defaults
- 20 newCap = DEFAULT_INITIAL_CAPACITY;
- 21 newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
- 22 }
- 23 // 计算新的resize上限
- 24 if (newThr == 0) {
- 25
- 26 float ft = (float)newCap * loadFactor;
- 27 newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
- 28 (int)ft : Integer.MAX_VALUE);
- 29 }
- 30 threshold = newThr;
- 31
-
32 Node
[] newTab = (Node [])new Node[newCap]; - 33 table = newTab;
- 34 if (oldTab != null) {
- 35 // 把每个bucket都移动到新的buckets中
- 36 for (int j = 0; j < oldCap; ++j) {
-
37 Node
e; - 38 if ((e = oldTab[j]) != null) {
- 39 oldTab[j] = null;
- 40 if (e.next == null)
- 41 newTab[e.hash & (newCap - 1)] = e;
- 42 else if (e instanceof TreeNode)
-
43 ((TreeNode
)e).split(this, newTab, j, oldCap); - 44 else { // 链表优化重hash的代码块
-
45 Node
loHead = null, loTail = null; -
46 Node
hiHead = null, hiTail = null; -
47 Node
next; - 48 do {
- 49 next = e.next;
- 50 // 原索引
- 51 if ((e.hash & oldCap) == 0) {
- 52 if (loTail == null)
- 53 loHead = e;
- 54 else
- 55 loTail.next = e;
- 56 loTail = e;
- 57 }
- 58 // 原索引+oldCap
- 59 else {
- 60 if (hiTail == null)
- 61 hiHead = e;
- 62 else
- 63 hiTail.next = e;
- 64 hiTail = e;
- 65 }
- 66 } while ((e = next) != null);
- 67 // 原索引放到bucket里
- 68 if (loTail != null) {
- 69 loTail.next = null;
- 70 newTab[j] = loHead;
- 71 }
- 72 // 原索引+oldCap放到bucket里
- 73 if (hiTail != null) {
- 74 hiTail.next = null;
- 75 newTab[j + oldCap] = hiHead;
- 76 }
- 77 }
- 78 }
- 79 }
- 80 }
- 81 return newTab;
- 82 }