HashMap的扩容机制是怎么样的?JDK7与JDK8有什么不同吗?
**
JDK 1.7的扩容条件是数组长度大于阈值且存在哈希冲突,在JDK 7中的扩容的源码如下:
void addEntry(int hash, K key, V value, int bucketIndex) {//数组长度大于阈值且存在哈希冲突(即当前数组下标有元素),就将数组扩容至2倍if ((size >= threshold) && (null != table[bucketIndex])) {resize(2 * table.length);hash = (null != key) ? hash(key) : 0;bucketIndex = indexFor(hash, table.length);}createEntry(hash, key, value, bucketIndex);}
而JDK 1.8扩容条件是数组长度大于阈值或链表转为红黑树且数组元素小于64时,源码中的体现如下所示:
//数组长度大于阈值,就扩容if (++size > threshold)resize();//链表转为红黑树时,若此时数组长度小于64,扩容数组if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)resize();
