IdentityHashMap
,使用什么的跟HashMap
相同,主要不同點在於:
- 數據結構:使用一個數組
table
來存儲key:value
,table[2k]
為key
,table[2k + 1]
為value
,也即:
key:value ==> table[2k]:table[2k + 1
](HashMap
使用數組 + 鏈表); IdentityHashMap
中的key
和value
通過==
來比較是否相等(HashMap
通過equals()
);IdentityHashMap
中的 hash沖突解決方式為線性探測法
(HashMap
為拉鏈法
);
具體,我們來看關鍵源碼:
/**
* 數據存儲結構:
* 使用一個數組table來存儲 key - value,第 table[2k] 為key, table[2k + 1] 為value,也即:
* key:value ==> table[2k]:table[2k + 1]
* IdentityHashMap 中的 key 和 value 通過 "==" 來比較是否相等(HashMap通過equals()來比較是否相等)
* @since 1.4
*/
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;
private transient Object[] table;// 存儲鍵值對的數組
private int size;
private transient int modCount;
private transient int threshold;
private static final Object NULL_KEY = new Object();
// 如果key為null,使用NULL_KEY代替
private static Object maskNull(Object key) {
return (key == null ? NULL_KEY : key);
}
// 如果之前key為null,被替換為NULL_KEY,現在替換回來
private static Object unmaskNull(Object key) {
return (key == NULL_KEY ? null : key);
}
public IdentityHashMap() {
init(DEFAULT_CAPACITY);
}
// 各種構造器方法,省略......
// 構造器中都會調用該方法
private void init(int initCapacity) {
threshold = (initCapacity * 2) / 3;
// 因為鍵值存儲在同一個數組中,所有數組大小為初始容量的2倍
table = new Object[2 * initCapacity];
}
private static int hash(Object x, int length) {
// 使用System.identityHashCode(x)計算hash值
int h = System.identityHashCode(x);
// 擾動;並且該表達式保證了元素的散列值是偶數
return ((h << 1) - (h << 8)) & (length - 1);
}
// hash沖突解決方式:線性探測法(linear-probe);因為key后面立馬是value,這里線性探測每次遞增2;
// 並且這里實現了循環探測;
private static int nextKeyIndex(int i, int len) {
return (i + 2 < len ? i + 2 : 0);
}
public V get(Object key) {
Object k = maskNull(key);
Object[] tab = table;
int len = tab.length;
int i = hash(k, len);
while (true) {
Object item = tab[i];
if (item == k)
return (V) tab[i + 1];// 如果第i個位置存儲為key,第i+1位置則存儲為對應的value
if (item == null)
return null;
// 線性探測
i = nextKeyIndex(i, len);
}
}
public boolean containsValue(Object value) {
Object[] tab = table;
for (int i = 1; i < tab.length; i += 2)
// value也使用"=="判斷相等
if (tab[i] == value && tab[i - 1] != null)
return true;
return false;
}
public V put(K key, V value) {
// 這里必須為 null 提供mask,因為在進行遍歷,get()等操作時,如果遇到key為null,則認為該位置沒有鍵值對
Object k = maskNull(key);
Object[] tab = table;
int len = tab.length;
int i = hash(k, len);
Object item;
// key為null,則認為該位置沒有鍵值對
while ((item = tab[i]) != null) {
if (item == k) {// 通過"=="判斷key相同
V oldValue = (V) tab[i + 1];
tab[i + 1] = value;
return oldValue;
}
i = nextKeyIndex(i, len);// 線性探測
}
modCount++;
// 如果第i個位置存儲為key,第i+1位置則存儲為對應的value
tab[i] = k;
tab[i + 1] = value;
if (++size >= threshold)
resize(len); // len == 2 * current capacity.
return null;
}
// 每次擴容為原來的2倍
private void resize(int newCapacity) {
int newLength = newCapacity * 2;
Object[] oldTable = table;
int oldLength = oldTable.length;
if (oldLength == 2 * MAXIMUM_CAPACITY) { // can't expand any further
if (threshold == MAXIMUM_CAPACITY - 1)
throw new IllegalStateException("Capacity exhausted.");
threshold = MAXIMUM_CAPACITY - 1; // Gigantic map!
return;
}
if (oldLength >= newLength)
return;
Object[] newTable = new Object[newLength];
threshold = newLength / 3;
// 對每個鍵值對重新進行散列到新數組中
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 = newTable;
}
public V remove(Object key) {
Object k = maskNull(key);
Object[] tab = table;
int len = tab.length;
int i = hash(k, len);
while (true) {
Object item = tab[i];
if (item == k) {
modCount++;
size--;
V oldValue = (V) tab[i + 1];
tab[i + 1] = null;
tab[i] = null;
// 第i個位置的鍵值對移除了,空出了位置,看后面是否有鍵值對要填補這個位置(有些鍵值對是因為線性探測導致其位置偏離了其hash值)
closeDeletion(i);
return oldValue;
}
if (item == null)
return null;
i = nextKeyIndex(i, len);
}
}
// 指定位置的鍵值對移除了,空出了位置,看后面是否有鍵值對要填補這個位置(有些鍵值對是因為線性探測導致其位置偏離了其hash值)
private void closeDeletion(int d) {
// Adapted from Knuth Section 6.4 Algorithm R
Object[] tab = table;
int len = tab.length;
Object item;
// d:空出來的鍵值對位置
// i:當前處理的鍵值對位置
// 直到key==null時才退出循環
for (int i = nextKeyIndex(d, len); (item = tab[i]) != null; i = nextKeyIndex(i, len)) {
int r = hash(item, len);
// i != r:證明item是被線性探測后放置在位置i;
// 這種情況 在插入時,線性探測出現了循環
// i<r:item通過線性探測到前面位置r前面去了
// ___i____r_____d____ i<r<=d
// ___d____i_____r____ d<=i<r
// 這個表達式相當於 (i < r) && !(i < d && d < r),也即 __i__d__r__(這種情況不能處理,因為這種情況下,因為線性探測是向后循環探測)
if ((i < r && (r <= d || d <= i))
||
(r <= d && d <= i)// 表示情況:___r____d____i____,建議先理解這種更簡單的情況
) {
// 把item對應的鍵值對放置到位置d;位置i為新空出來的鍵值對位置;
tab[d] = item;
tab[d + 1] = tab[i + 1];
tab[i] = null;
tab[i + 1] = null;
d = i;
}
}
}
public void clear() {
modCount++;
Object[] tab = table;
for (int i = 0; i < tab.length; i++)
tab[i] = null;
size = 0;
}
// Object方法代碼,省略
// 常用Map代碼,省略
// 序列化相關代碼,省略
}