標籤:
1、HashMap怎麼存資料在HashMap中使用內部靜態類(Entry)數組table存資料,即Entry<K,V>[] table;
static class Entry<K,V> implements Map.Entry<K,V> { final K key; V value; Entry<K,V> next; int hash; Entry(int h, K k, V v, Entry<K,V> n) { value = v; next = n; key = k; hash = h; }}Entry類中儲存了key、value、key的hash值和下一個Entry的引用(拉鏈法解決hash衝突)。
2、put方法put方法的內容
public V put(K key, V value) { if (key == null) return putForNullKey(value);//對key為空白的值會被放在數組的下表為0的位置上,hash值也為0 int hash = hash(key); int i = indexFor(hash, table.length); for (Entry<K,V> e = table[i]; e != null; e = e.next) { Object k; 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的方法處理過程是先找這個key對應的hash是否存在,如果存在就判斷key是否相同,如果key相同就用新的value替換舊的value。
如果這個key對應的hash不存在或key不相同,就添加到數組table中下表i的位置上
3、addEntry方法addEntry方法源碼
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);//在指定的下標添加元素 }threshold是閾值的意思,這個值有兩個參數決定:capacity(容量,預設16,以後所有的取值都是2的n次方), loadFactor(負載係數,預設0.75,簡單來數就是空間利用率),threshold=capacity*loadFactor,例如預設情況下capacity=16,loadFactor=0.75,所以threshold=12,當HashMap中的元素個數大於等於12時,就有可能擴容,變為原來容量的兩倍,用resize方法調整。
4、resize方法resize方法源碼
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]; boolean oldAltHashing = useAltHashing; useAltHashing |= sun.misc.VM.isBooted() && (newCapacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD); boolean rehash = oldAltHashing ^ useAltHashing; transfer(newTable, rehash);//轉移方法 table = newTable; threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1); }
可以看到閥值threshold的最大值為Integer.MAX_VALUE。當現在的容量capacity已經達到最大值2^30時,不再進行擴容,並把閥值設為int的最大值。如果沒有達到容量的最大值就擴容為原來的兩倍,並把oldTable數組中的元素轉移到新的newTable數組中,重新計算閥值。
5、transfer方法transfer方法源碼
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); } int i = indexFor(e.hash, newCapacity); e.next = newTable[i]; newTable[i] = e; e = next; } } }
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
java中HashMap滿了會怎樣