HashMap的resize自动扩容

在之前学习的HashMap触发红黑树条件的知识点中,有一个步骤是resize(), 再来了解一下这块的知识

HashMap是JAVA最常用的集合之一,用来存储Key-Value这种键值对形式的数据,内部通过哈希表,让存取的效率最好的时候可以达到O(1),实际使用中可能存在hash冲突,引入了链表和红黑树结构,让效率最差也不低于O(logn)。

集合的底层是基于数组、链表这种基础的数据结构,集合在容量不足的情况下,会触发动态扩容来保证有足够的空间存储数据,动态扩容因为涉及到一系列 数据调整拷贝等, 实际上是比较繁琐耗时的操作,所以使用时能够预估数据量的范围,合理的通过构造方法,指定集合的初始容量,保证接下来的操作不会触发动态扩容。

先来看看HashMap初始化的时候,都做了哪些事情

/**
* Constructs an empty <tt>HashMap</tt> with the specified initial
* capacity and the default load factor (0.75).
*
* @param initialCapacity the initial capacity.
* @throws IllegalArgumentException if the initial capacity is negative.
*/
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}

HashMap提供了一个指定初始化容量的构造方法,这个方法内部实际上是调用了另一个构造方法中,带有load factor的构造方法,默认的load factor是0.75
/**
* Constructs an empty <tt>HashMap</tt> with the specified initial
* capacity and load factor.
*
* @param initialCapacity the initial capacity
* @param loadFactor the load factor
* @throws IllegalArgumentException if the initial capacity is negative
* or the load factor is nonpositive
*/
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
this.threshold = tableSizeFor(initialCapacity);
}

其中的threshold是用来存储触发HashMap扩容的阈值,也就是说,当hashMap中存储的元素个数达到threshold时,就会触发自动扩容

从上面的方法中可以看出,HashMap的初始化,并不是直接使用传入的 initialCapacity,而是用这个值经过方法 tableSizeFor()处理后,得到一个threshold

再来看看这个方法的处理逻辑:

/**
* Returns a power of two size for the given target capacity.
*/
static final int tableSizeFor(int cap) {
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}

可以看到实际上是逐步的位运算,让得到的返回值始终保持在2的N次幂,这么做的目的是为了在后续的扩容中,快速计算数据在扩容后的新表中的位置
比如说外部纯如的数字是10000,那么在经过计算后,会变成最低的2的14次幂=16384,乘以默认的负载因子0.75f,在不扩容的前提下,可存储的数据量是
16384*0.75 = 12288
所以当初始化HashMap时,传入10000的容量,实际在存放10000个数据量的时候是不会触发自动扩容的

那么另外的一种场景,我们传入的初始容量为1000,情况会是怎么样呢?再来分析一下:
在HashMap的构造方法中,threhold为扩容的阈值,在构造方法中由tableSizeFor方法计算后直接赋值,所以如果初始传入1000,那么通过构造函数的计算得到的
threhold为1024,但是HashMap在此时并没有直接使用,这个时候load factor也没有使用,那什么时候使用的这些参数呢,再来看看HashMap的处理逻辑:
/**
* 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;
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;
}

在HashMap中,所有的数据都是通过内部的成员变量table数组来存储的,,在jdk1.8后,table的类型有调整,但是没有改变数组的基本结构,三者之间的关系是:
table.size = threshold * loadFactor
在HashMap中,table的初始化也是在resize方法中,也就是说,resize方法不仅承担了动态扩容的逻辑,也承担了table的初始化,在上面的源码中,可以看到,当我们第一次
调用put方法存储数据的时候,如果发现table为null,则会调用resize去初始化,在resize的方法中,调整了threshold的值,完成了初始化:
/**
* 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<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}

当我们指定了初始容量,且table未被初始化,这个时候oldThr(代表扩容的阈值)通过threshol赋值,不为0,oldCap(代表table的容量)=0,所以逻辑会走到:
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;

会将oldThr赋值给newCap,也就是新创建 table会是我们构造的HashMap时指定的容量值
接着往下走
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;


newThr=0,会通过装载因子loadFactor调整新的阈值,最后将使用loadFactor调整后的阈值保存到了threshold中,并通过newCap创建新的数组,并将其指定到table中,完成table的初始化
所以再初始化 时候,传入的initialCapacity 经过位运算被赋值给threshold,但是他实际上是table的大小,并且最终会通过loadFactor重新调整threshold
当传入初始容量为1000,只是表示table数组为1000,扩容依据的阈值会在resize中调整为1024*0.75=768
所以当存入1000条数据时候,容量不足,还是会触发一次自动扩容

所以当按照实际当业务初始化一个容量当时候,为了避免自动扩容,将我们预期当容量除以0.75,得到当数值作为初始化容量。

HashMap的初始化容量默认是16.

最开始的条件,当传入10000,经过resize计算后的threshols是16384*0.75 = 12288 所以存入10000条数据不会触发自动扩容



猜你喜欢

转载自www.cnblogs.com/wangflower/p/12236481.html