擴容必須知足兩個條件java
下面是put方法數組
public V put(K key, V value) { //判斷當前Hashmap(底層是Entry數組)是否存值(是否爲空數組) if (table == EMPTY_TABLE) { inflateTable(threshold);//若是爲空,則初始化 } //判斷key是否爲空 if (key == null) return putForNullKey(value);//hashmap容許key爲空 //計算當前key的哈希值 int hash = hash(key); //經過哈希值和當前數據長度,算出當前key值對應在數組中的存放位置 int i = indexFor(hash, table.length); for (Entry<K,V> e = table[i]; e != null; e = e.next) { Object k; //若是計算的哈希位置有值(及hash衝突),且key值同樣,則覆蓋原值value,並返回原值value if (e.hash == hash && ((k = e.key) == key || key.equals(k))) { V oldValue = e.value; e.value = value; e.recordAccess(this); return oldValue; } } modCount++; //存放值的具體方法 addEntry(hash, key, value, i); return null; }
在put方法中有調用addEntry方法,這方法裏面是具體存值,在存值以前還須要判斷是否擴容this
void addEntry(int hash, K key, V value, int bucketIndex) { //一、判斷當前個數是否大於等於閾值 //二、當前存放是否發生哈希碰撞 //若是上面兩個條件否發生,那麼就擴容 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); }
若是須要擴容,調用擴容的方法resize()code
void resize(int newCapacity) { Entry[] oldTable = table; int oldCapacity = oldTable.length; //判斷是否有超出擴容的最大值,若是達到最大值則不進行擴容操做 if (oldCapacity == MAXIMUM_CAPACITY) { threshold = Integer.MAX_VALUE; return; } Entry[] newTable = new Entry[newCapacity]; // transfer()方法把原數組中的值放到新數組中 transfer(newTable, initHashSeedAsNeeded(newCapacity)); //設置hashmap擴容後爲新的數組引用 table = newTable; //設置hashmap擴容新的閾值 threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1); }
transfer()在實際擴容時候把原來數組中的元素放入新的數組中ci
void transfer(Entry[] newTable, boolean rehash) { int newCapacity = newTable.length; for (Entry<K,V> e : table) { while(null != e) { Entry<K,V> next = e.next; if (rehash) { e.hash = null == e.key ? 0 : hash(e.key); } //經過key值的hash值和新數組的大小算出在當前數組中的存放位置 int i = indexFor(e.hash, newCapacity); e.next = newTable[i]; newTable[i] = e; e = next; } } }
Hashmap的擴容須要知足兩個條件:當前數據存儲的數量(即size())大小必須大於等於閾值;當前加入的數據是否發生了hash衝突。 由於上面這兩個條件,因此存在下面這些狀況 (1)、就是hashmap在存值的時候(默認大小爲16,負載因子0.75,閾值12),可能達到最後存滿16個值的時候,再存入第17個值纔會發生擴容現象,由於前16個值,每一個值在底層數組中分別佔據一個位置,並無發生hash碰撞。源碼
(2)、固然也有可能存儲更多值(超多16個值,最多能夠存26個值)都尚未擴容。原理:前11個值所有hash碰撞,存到數組的同一個位置(這時元素個數小於閾值12,不會擴容),後面全部存入的15個值所有分散到數組剩下的15個位置(這時元素個數大於等於閾值,可是每次存入的元素並無發生hash碰撞,因此不會擴容),前面11+15=26,因此在存入第27個值的時候才同時知足上面兩個條件,這時候纔會發生擴容現象。hash
注:jdk版本1.7it