hashmap的put方法源碼分析
put主源碼如下:
public V put(K key, V value) { if (key == null) return putForNullKey(value); int hash = hash(key.hashCode()); 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; }
1.1、putForNullKey():當key為null的時候自動轉向putForNullKey()方法,用來處理null鍵,將他們放到table[0]的位置,下面的是putForNullKey()方法,進來遍歷entry鏈表,如果遍歷後,發現沒有key沒為nulll存在,則直接添加一個entry,鍵為null,值為新的value;而當遍歷後,發現key有null的時候,就返回就值,讓新值覆蓋舊值。
private V putForNullKey(V value) { for (Entry<K,V> e = table[0]; e != null; e = e.next) { if (e.key == null) { V oldValue = e.value; e.value = value; e.recordAccess(this); return oldValue; } } modCount++; addEntry(0, null, value, 0); return null; }
1.2當傳入的鍵不為null的時候,先hash一下key的hashcode值(用來避免重寫hashcode方法的不完美,保證hash散布的均勻),然後使用indexFor方法來找到對應在table[]上的位置。
indexFor源碼:它沒有對hash表的長度取余而使用了位運算來得到索引,這是為什麽呢?因為length在hashmap中默認為2的冪次方,所以length-1所得到的二進制都是1構成的,所以hash和這個length-1做與運算其實也是對hash表的長度取余。位運算快於四則運算。(這也是為什麽要去size為2的冪次方的原因,因為如果取其他數值,hash碰撞幾率增大,可能size的二進制某一位上是0,導致好幾個table位置無法存放數據,造成空間浪費)。
static int indexFor(int h, int length) { return h & (length-1); }
1.3、找到新元素的table[index]後,就遍歷該位置上的entry鏈;如果僅僅使用equals進行鏈上比較效率會很低,所以我們先使用hash來比較過濾。遇到相同的值就覆蓋,返回舊值。如果沒有相同值就直接addentry()進行頭插法插入鏈表。
1.4、增加entry方法addentry():addentry的源碼:判斷當前table的size大於等於邊界值並且index位置上不為空,就2倍擴容table他的大小,然後再根據傳入的hash,key,value重新定向這個元素的位置。創建entry並創建。
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); }
1.4擴容resize(擴容條件,當前容量大於邊界值,並且添加的index對應的table上不為null)
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(newTable, initHashSeedAsNeeded(newCapacity)); table = newTable; threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1); }
1.5、關鍵是空表擴容後的拷貝到新表的方法transfer方法,下面是源碼:將table上的entry進行遍歷,傳入的rehash用來判斷是否用來重新hash,為true的話就判斷key是否為null,如果為null就hash值為0,不為null就重hash,然後重定位index,然後頭插法放到對應的位置上
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; } } }
1.6、最後進行createEntry(),頭插法插入,最後將e傳入新table[]中,表示指針指向舊值。
void createEntry(int hash, K key, V value, int bucketIndex) { Entry<K,V> e = table[bucketIndex]; table[bucketIndex] = new Entry<>(hash, key, value, e); size++; }
至此全部完成
hashmap的put方法源碼分析