關於HashMap源碼解析,參考http://www.iteye.com/topic/539465,和http://grunt1223.iteye.com/blog/544497,以及http://www.ibm.com/developerworks/cn/java/j-lo-hash/?open&cm_mmc=6505-_-n-_-vrm_newsletter-_-10104_142587&cmibm_em=dm:0:10631101#ibm-pcon,比較好的是前2個
總體來說,是一個數組下面掛的鏈表,採用鏈式結構解決衝突,精妙之處有2個:
1、
static int indexFor(int paramInt1, int paramInt2) { return paramInt1 & paramInt2 - 1; }
如同上面連結所講,平均分配hash到數組上的位置
2、
靜態內部類
《effective java》22條所講,優先使用靜態內部類,使用Entry內部類來儲存元素,對外隱藏所有實現細節
static class Entry<K, V> implements Map.Entry<K, V> { final K key; V value; Entry<K, V> next; final int hash; Entry(int paramInt, K paramK, V paramV, Entry<K, V> paramEntry) { this.value = paramV; this.next = paramEntry; this.key = paramK; this.hash = paramInt; } public final K getKey(); public final V getValue(); public final V setValue(V paramV); public final boolean equals(Object paramObject); public final int hashCode(); public final String toString() void recordAccess(HashMap<K, V> paramHashMap) { } void recordRemoval(HashMap<K, V> paramHashMap) { } }