1
2
3
4
5
6
觀察jdk中HashMap的源碼,我們知道極限值為2的31次方。
void resize(int newCapacity) {
Entry[] oldTable = table;
int oldCapacity = oldTable.length;
if (oldCapacity == MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;//將threshold置為Integer.MAX_VALUE
return;//當HashMap的容量已經是2的31次方的時候,直接返回。
}
Entry[] newTable = new Entry[newCapacity];
transfer(newTable);
table = newTable;
threshold = (int)(newCapacity * loadFactor);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
觀察jdk中源碼可發現當HashMap的容量已經是2的31次方的時候,就不會在進行擴容了。
/**
* The next size value at which to resize (capacity * load factor).
* @serial
*/
int threshold;
1
2
3
4
5
如上為對threshold的定義。
/**
* Adds a new entry with the specified key, value and hash code to
* the specified bucket. It is the responsibility of this
* method to resize the table if appropriate.
*
* Subclass overrides this to alter the behavior of put method.
*/
void addEntry(int hash, K key, V value, int bucketIndex) {
Entry<K,V> e = table[bucketIndex];
table[bucketIndex] = new Entry<K,V>(hash, key, value, e);
if (size++ >= threshold)
resize(2 * table.length);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
觀察如上源碼可知,當添加完元素后的容量大於threshold,就調用resize方法。
---------------------
作者:liudezhicsdn
來源:CSDN
原文:https://blog.csdn.net/liudezhicsdn/article/details/51234292?utm_source=copy
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!