IdentityHashMap是Map接口的实现。不同于HashMap的,这里采用参考平等。
●在HashMap中如果两个元素是相等的,则key1.equals(key2)
●在IdentityHashMap中如果两个元素是相等的,则key1 == key2
源码如下
public V put(K key, V value) {
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) { // 这里判断是是否 ==而hashMap判断是否equals
@SuppressWarnings("unchecked")
V oldValue = (V) tab[i + 1];
tab[i + 1] = value;
return oldValue;
}
}
final int s = size + 1;
// Use optimized form of 3 * s.
// Next capacity is len, 2 * current capacity.
if (s + (s << 1) > len && resize(len))
continue retryAfterResize;
modCount++;
tab[i] = k;
tab[i + 1] = value;
size = s;
return null;
}
}