一、前言
前面已經分析了HashMap與LinkedHashMap,現在我們來分析不太常用的IdentityHashMap,從它的名字上也可以看出來用於表示唯一的HashMap,仔細分析了其源碼,發現其數據結構與HashMap使用的數據結構完全不同,因為在繼承關系上面,他們兩沒有任何關系。下面,進入我們的分析階段。
二、IdentityHashMap示例

import java.util.Map; import java.util.HashMap; import java.util.IdentityHashMap; public class IdentityHashMapTest { public static void main(String[] args) { Map<String, String> hashMaps = new HashMap<String, String>(); Map<String, String> identityMaps = new IdentityHashMap<String, String>(); hashMaps.put(new String("aa"), "aa"); hashMaps.put(new String("aa"), "bb"); identityMaps.put(new String("aa"), "aa"); identityMaps.put(new String("aa"), "bb"); System.out.println(hashMaps.size() + " : " + hashMaps); System.out.println(identityMaps.size() + " : " + identityMaps); } }
運行結果:
1 : {aa=bb}
2 : {aa=bb, aa=aa}
說明:IdentityHashMap只有在key完全相等(同一個引用),才會覆蓋,而HashMap則不會。
三、IdentityHashMap數據結構
說明:IdentityHashMap的數據很簡單,底層實際就是一個Object數組,在邏輯上需要看成是一個環形的數組,解決沖突的辦法是:根據計算得到散列位置,如果發現該位置上已經有元素,則往后查找,直到找到空位置,進行存放,如果沒有,直接進行存放。當元素個數達到一定閾值時,Object數組會自動進行擴容處理。
四、IdentityHashMap源碼分析
4.1 類的繼承關系
public class IdentityHashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, java.io.Serializable, Cloneable
說明:繼承了AbstractMap抽象類,實現了Map接口,可序列化接口,可克隆接口。
4.2 類的屬性

public class IdentityHashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, java.io.Serializable, Cloneable { // 缺省容量大小 private static final int DEFAULT_CAPACITY = 32; // 最小容量 private static final int MINIMUM_CAPACITY = 4; // 最大容量 private static final int MAXIMUM_CAPACITY = 1 << 29; // 用於存儲實際元素的表 transient Object[] table; // 大小 int size; // 對Map進行結構性修改的次數 transient int modCount; // null key所對應的值 static final Object NULL_KEY = new Object(); }
說明:可以看到類的底層就是使用了一個Object數組來存放元素。
4.3 類的構造函數
1. IdentityHashMap()型構造函數

public IdentityHashMap() { init(DEFAULT_CAPACITY); }
2. IdentityHashMap(int)型構造函數

public IdentityHashMap(int expectedMaxSize) { if (expectedMaxSize < 0) throw new IllegalArgumentException("expectedMaxSize is negative: " + expectedMaxSize); init(capacity(expectedMaxSize)); }
3. IdentityHashMap(Map<? extends K, ? extends V>)型構造函數

public IdentityHashMap(Map<? extends K, ? extends V> m) { // 調用其他構造函數 this((int) ((1 + m.size()) * 1.1)); putAll(m); }
4.4 重要函數分析
1. capacity函數

// 此函數返回的值是最小大於expectedMaxSize的2次冪 private static int capacity(int expectedMaxSize) { // assert expectedMaxSize >= 0; return (expectedMaxSize > MAXIMUM_CAPACITY / 3) ? MAXIMUM_CAPACITY : (expectedMaxSize <= 2 * MINIMUM_CAPACITY / 3) ? MINIMUM_CAPACITY : Integer.highestOneBit(expectedMaxSize + (expectedMaxSize << 1)); }
說明: 此函數返回的值是最小的且大於expectedMaxSize的2次冪的值。
2. hash函數

// hash函數,由於length總是為2的n次冪,所以 & (length - 1)相當於對length取模 private static int hash(Object x, int length) { int h = System.identityHashCode(x); // Multiply by -127, and left-shift to use least bit as part of hash return ((h << 1) - (h << 8)) & (length - 1); }
說明:hash函數用於散列,並且保證元素的散列值會在數組偶次索引。
3. get函數

public V get(Object key) { // 保證null的key會轉化為Object(NULL_KEY) Object k = maskNull(key); // 保存table Object[] tab = table; int len = tab.length; // 得到key的散列位置 int i = hash(k, len); // 遍歷table,解決散列沖突的辦法是若沖突,則往后尋找空閑區域 while (true) { Object item = tab[i]; // 判斷是否相等(地址是否相等) if (item == k) // 地址相等,即完全相等的兩個對象 return (V) tab[i + 1]; // 對應散列位置的元素為空,則返回空 if (item == null) return null; // 取下一個Key索引 i = nextKeyIndex(i, len); } }
說明:該函數比較key值是否完全相同(對象類型則是否為同一個引用,基本類型則是否內容相等)
4. nextKeyIndex函數

// 下一個Key索引 private static int nextKeyIndex(int i, int len) { // 往后移兩個單位 return (i + 2 < len ? i + 2 : 0); }
說明:此函數用於發生沖突時,取下一個位置進行判斷。
5. put函數

public V put(K key, V value) { // 保證null的key會轉化為Object(NULL_KEY) final Object k = maskNull(key); retryAfterResize: for (;;) { final Object[] tab = table; final int len = tab.length; int i = hash(k, len); for (Object item; (item = tab[i]) != null; i = nextKeyIndex(i, len)) { if (item == k) { // 經過hash計算的項與key相等 @SuppressWarnings("unchecked") // 取得值 V oldValue = (V) tab[i + 1]; // 將value存入 tab[i + 1] = value; // 返回舊值 return oldValue; } } // 大小加1 final int s = size + 1; // Use optimized form of 3 * s. // Next capacity is len, 2 * current capacity. // 如果3 * size大於length,則會進行擴容操作 if (s + (s << 1) > len && resize(len)) // 擴容后重新計算元素的值,尋找合適的位置進行存放 continue retryAfterResize; // 結構性修改加1 modCount++; // 存放key與value tab[i] = k; tab[i + 1] = value; // 更新size size = s; return null; } }
說明:若傳入的key在表中已經存在了(強調:是同一個引用),則會用新值代替舊值並返回舊值;如果元素個數達到閾值,則擴容,然后再尋找合適的位置存放key和value。
6. resize函數

private boolean resize(int newCapacity) { // assert (newCapacity & -newCapacity) == newCapacity; // power of 2 int newLength = newCapacity * 2; // 保存原來的table Object[] oldTable = table; int oldLength = oldTable.length; // 舊表是否為最大容量的2倍 if (oldLength == 2 * MAXIMUM_CAPACITY) { // can't expand any further // 之前元素個數為最大容量,拋出異常 if (size == MAXIMUM_CAPACITY - 1) throw new IllegalStateException("Capacity exhausted."); return false; } // 舊表長度大於新表長度,返回false if (oldLength >= newLength) return false; // 生成新表 Object[] newTable = new Object[newLength]; // 將舊表中的所有元素重新hash到新表中 for (int j = 0; j < oldLength; j += 2) { Object key = oldTable[j]; if (key != null) { Object value = oldTable[j+1]; oldTable[j] = null; oldTable[j+1] = null; int i = hash(key, newLength); while (newTable[i] != null) i = nextKeyIndex(i, newLength); newTable[i] = key; newTable[i + 1] = value; } } // 新表賦值給table table = newTable; return true; }
說明:當表中元素達到閾值時,會進行擴容處理,擴容后會舊表中的元素重新hash到新表中。
7. remove函數

public V remove(Object key) { // 保證null的key會轉化為Object(NULL_KEY) Object k = maskNull(key); Object[] tab = table; int len = tab.length; // 計算hash值 int i = hash(k, len); while (true) { Object item = tab[i]; // 找到key相等的項 if (item == k) { modCount++; size--; @SuppressWarnings("unchecked") V oldValue = (V) tab[i + 1]; tab[i + 1] = null; tab[i] = null; // 刪除后需要進行后續處理,把之前由於沖突往后挪的元素移到前面來 closeDeletion(i); return oldValue; } // 該項為空 if (item == null) return null; // 下一項 i = nextKeyIndex(i, len); } }
8. closeDeletion函數

private void closeDeletion(int d) { // Adapted from Knuth Section 6.4 Algorithm R Object[] tab = table; int len = tab.length; // Look for items to swap into newly vacated slot // starting at index immediately following deletion, // and continuing until a null slot is seen, indicating // the end of a run of possibly-colliding keys. Object item; // 把該元素后面符合移動規定的元素往前面移動 for (int i = nextKeyIndex(d, len); (item = tab[i]) != null; i = nextKeyIndex(i, len) ) { // The following test triggers if the item at slot i (which // hashes to be at slot r) should take the spot vacated by d. // If so, we swap it in, and then continue with d now at the // newly vacated i. This process will terminate when we hit // the null slot at the end of this run. // The test is messy because we are using a circular table. int r = hash(item, len); if ((i < r && (r <= d || d <= i)) || (r <= d && d <= i)) { tab[d] = item; tab[d + 1] = tab[i + 1]; tab[i] = null; tab[i + 1] = null; d = i; } } }
說明:在刪除一個元素后會進行一次closeDeletion處理,重新分配元素的位置。
下圖表示在closeDeletion前和closeDeletion后的示意圖
說明:假設:其中,("aa" -> "aa")經過hash后在第0項,("bb" -> "bb")經過hash后也應該在0項,發生沖突,往后移到第2項,("cc" -> "cc")經過hash后在第2項,發生沖突,往后面移動到第4項,("gg" -> "gg")經過hash在第2項,發生沖突,往后移動到第6項,("dd" -> "dd")在第8項,("ee" -> "ee")在第12項。當刪除("bb" -> "bb")后,進行處理后的元素布局如右圖所示。
五、總結
IdentityHashMap與HashMap在數據結構上很不相同,並且處理hash沖突的方法也不相同。其中,IdentityHashMap只有當key為同一個引用時才認為是相同的,而HashMap還包括equals相等,即內容相同。