標籤:
今天來看下HashMap源碼,先從put方法入手:
public V put(K key, V value) { if (table == EMPTY_TABLE) { inflateTable(threshold); } if (key == null) return putForNullKey(value); 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; }
第一部分主要完成對空容器的一個初始化:
private void inflateTable(int toSize) { // Find a power of 2 >= toSize int capacity = roundUpToPowerOf2(toSize); threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1); table = new Entry[capacity]; initHashSeedAsNeeded(capacity); }
如果key為null時會將索引值對插在table[0]這個位置,可見null可以作為HashMap的索引值,
int hash = hash(key);int i = indexFor(hash, table.length);
這兩行主要是為了在table數組中定位,其中可以看出String的hash值只跟字元內容有關。
table數組的每個元素都是一個Entry<K,V>鏈表,
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; } }
這一段就是要驗證插入前HashMap是否存在與插入元素相同的索引值,如果有就更新值,如果沒有
addEntry(hash, key, value, i);
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); }
如果size超過threshold就擴容否則將建立元素插入都鏈表頭部。
詳細參考http://www.cnblogs.com/matrix-skygirl/archive/2013/01/17/2864919.html
HashMap源碼解析