探索IdentityHashMap底层实现
前沿
我也是第一次认识IdentityHashMap,在工作中从未使用过它,所以对它的使用场景可能并不是很了解,本文也仅仅针对基于JDK1.8的源码进行探索。IdentityHashMap的数据结构应该是如图所示:

这个数据结构是我在看源码之前看了几篇别人写的文章所了解到的,个人喜欢在看源码对目标有所了解的习惯,紧接着才去深入它。
阅读注释

在IdentityHashMap中,对于两个键只有在k1 == k2成立时才认为是相等的,而在HashMap中确实k1.equals(k2)成立是才被认为相等,前者是引用相等,而后者是对象相等。


Identity可用于序列化或深拷贝或对象代理。

键值对允许存放null,同样也是无序的。

IdentityHashMap属于非线程安全,和集合中的其他类一样迭代器都可能发生快速失败。

线性探针哈希表,这是对其数据结构的称呼。
数据结构
//可序列化、克隆
public class IdentityHashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, java.io.Serializable, Cloneable {
/**
* 默认键值对个数
* 虽然注释上写着是默认初始容量,但当你发现有这样子的一段代码时:table = new Object[2 * initCapacity],你就会明白默认初始容量应该是64
* 容量大小必须是2的幂次方,在添加节点时会先判断当前节点的个数是否超过了容量的1/3,所以我认为1/3是加载因子
*
* 为什么必须是2的幂次方?
* 在计算索引时用&代码了%,提升了效率,不过这导致了一个前提,就是必须是2的幂次方,为了是能够取到容量区间中的每个索引,有人将这种做法称为均匀分布
*/
private static final int DEFAULT_CAPACITY = 32;
/**
* 最小键值对个数
*
* 为什么最小是4?
* 假设手动指定容量大小是1,则初始容量应该是2,在添加第一个节点时会先判断当前节点的个数是否超过了容量的1/3,很显然,2 * 1/3的结果都不足1,所以它会先扩容,扩容后再添加节点,由于扩容是需要消耗一定的成本,为何不在初始化时就设定较 * 高的值来避免此次扩容;那么如果指定容量大小是2呢? 4 * 1/3 不足2,因为它的数据结构是同时存储key与value,所以在存储value时也必定会扩容,故也不行;那3就更不行了,毕竟要是2的幂次方,所以4属于最小指定容量值
*/
private static final int MINIMUM_CAPACITY = 4;
/**
* 最大键值对个数
* 虽然注释上写着是最大容量,但实际上并不是,此数值用于当构造函数中指定的容量过高时会直接该数值,而当你发现有这样子一句代码时:table = new Object[2 * initCapacity]; 你就会发现实际上最大的容量应该是 1<<30才对
* 实际上,线性探针表中能存储的节点个数不能超过 1<<<30 - 1 个,因为它至少有一个位置是存储了null,用来避免死循环
*/
private static final int MAXIMUM_CAPACITY = 1 << 29;
/**
* 线性探针表
*/
transient Object[] table;
/**
* 线性探针表中存储的节点个数
*/
int size;
/**
* 结构被修改的次数
* 该成员属性是用于检测迭代器的快速失败
*/
transient int modCount;
/**
* 代表键为null
*/
static final Object NULL_KEY = new Object();
/**
* 缓存entrySet方法的返回值
*/
private transient Set<Map.Entry<K,V>> entrySet;
}
构造函数
/**
* 采用默认键值对个数初始化
*/
public IdentityHashMap() {
init(DEFAULT_CAPACITY);
}
/**
* 指定键值对个数来初始化
* @param expectedMaxSize 指定键值对个数
*/
public IdentityHashMap(int expectedMaxSize) {
if (expectedMaxSize < 0)
throw new IllegalArgumentException("expectedMaxSize is negative: "
+ expectedMaxSize);
init(capacity(expectedMaxSize));
}
/**
* 指定键值对个数进行初始化,并将指定集合添加到线性探针表中
* @param m 指定集合
*/
public IdentityHashMap(Map<? extends K, ? extends V> m) {
// Allow for a bit of growth
this((int) ((1 + m.size()) * 1.1));
putAll(m);
}
简单方法
/**
* 倘若键为null则采用NULL_KEY作为键
* 正如方法名一样,隐藏Null
* @param key 指定键
* @return NULL_KEY或指定键
*/
private static Object maskNull(Object key) {
return (key == null ? NULL_KEY : key);
}
/**
* 倘若键为NULL_KEY则返回null
* 正如方法名一样,揭露Null
* @param key 线性探针表中的键
* @return null或指定键
*/
static final Object unmaskNull(Object key) {
return (key == NULL_KEY ? null : key);
}
/**
* 调整指定键值对个数
* Integer.highestOneBit 返回只含有二进制中最高位(从左到右第一个数字为1)的十进制,如15对应的二进制是1111,结果是1000,也就是数字8
* 这里有一点我觉得代码写的不够完美,假设expectedMaxSize = 3,意思我可能要存储3个键值对,而它最终的容量是16,那么在我添加最后一对键值对时,它仍然会进行扩容,个人觉得设计的不够完美
* @param expectedMaxSize 指定键值对个数
* @return 调整后的键值对个数
*/
private static int capacity(int expectedMaxSize) {
return
(expectedMaxSize > MAXIMUM_CAPACITY / 3) ? MAXIMUM_CAPACITY :
(expectedMaxSize <= 2 * MINIMUM_CAPACITY / 3) ? MINIMUM_CAPACITY :
Integer.highestOneBit(expectedMaxSize + (expectedMaxSize << 1));
}
/**
* 指定键值对个数来初始化哈希探针表
* 由于参数代表着键值对个数,相当于是2倍的节点个数,故在初始化时 * 2
* @param initCapacity 指定键值对个数
*/
private void init(int initCapacity) {
table = new Object[2 * initCapacity];
}
/**
* 获取哈希探针表中节点的个数
* @return 节点的个数
*/
public int size() {
return size;
}
/**
* 判断哈希探针表是否为空
* @return 哈希探针表是否为空
*/
public boolean isEmpty() {
return size == 0;
}
/**
* 在指定区间内获取偶数索引位置
* 为什么是偶数位置?
* 因为它的数据结构是按照 | key | value | key1 | value1 | 的形式进行存储,导致了键是存储在偶数位置上,而值是存储在奇数位置上
* 它采用的System.identityHashCode,该方法的结果与Object#hashCode的结果是一样的,只不过这样子就调不到开发人员自己覆写的hashCode方法
* @param x 指定键
* @param length 指定容量大小
* @return 偶数索引位置
*/
private static int hash(Object x, int length) {
int h = System.identityHashCode(x);
/**
* (h << 1) - (h <<8)
* h * Math.pow(2,1) - h * Math.pow(2,8) -> -h * (Math.pow(2,8) - Math.pow(2,1)) -> -h * 2 * (Math.pow(2,7) - 1) -> -h * 2 * 127 -> -h * 127 * 2
* 简化后的结果正好跟注释对应上,不过它始终没解释为啥是乘以-127,目前只知道 * 2是一定会得到偶数,因为它相当于进行了左移,去掉了最右边的一位,即1
* 然后偶数 & (length - 1) 最终是确定索引只可能是该区间内上的某一个偶数位置
*/
return ((h << 1) - (h << 8)) & (length - 1);
}
/**
* 获取下一个偶数索引位置
* 若下一个偶数索引位置超过了哈希探针表的容量大小,则从头开始,相当于在循环遍历哈希探针表
* @param i 当前索引位置
* @param len 表的容量大小
* @return 下一个偶数索引位置
*/
private static int nextKeyIndex(int i, int len) {
return (i + 2 < len ? i + 2 : 0);
}
/**
* 对哈希探针表进行扩容
* 新表是旧表的2倍,原来在旧表中节点重新散列到新表上
* @param newCapacity 指定容量大小
* @return 是否扩容成功
*/
private boolean resize(int newCapacity) {
int newLength = newCapacity * 2;
Object[] oldTable = table;
int oldLength = oldTable.length;
if (oldLength == 2 * MAXIMUM_CAPACITY) {
if (size == MAXIMUM_CAPACITY - 1) //最大节点的个数不能超过 MAXIMUM_CAPACITY - 1,因为有一个位置要存储Null,避免死循环
throw new IllegalStateException("Capacity exhausted.");
return false;
}
if (oldLength >= newLength)
return false;
Object[] newTable = new Object[newLength];
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;
return true;
}
/**
* 哈希探针表中是否包含指定键
* @param key 指定键
* @return 是否包含指定键
*/
public boolean containsKey(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 true;
if (item == null)
return false;
i = nextKeyIndex(i, len);
}
}
/**
* 哈希探针表中是否包含指定值
* @param value 指定值
* @return 是否包含指定值
*/
public boolean containsValue(Object value) {
Object[] tab = table;
for (int i = 1; i < tab.length; i += 2)
if (tab[i] == value && tab[i - 1] != null)
return true;
return false;
}
/**
* 哈希探针表中是否包含指定键值对
* @param key 指定键
* @param value 指定值
* @return 是否包含指定键值对
*/
private boolean containsMapping(Object key, Object value) {
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 tab[i + 1] == value;
if (item == null)
return false;
i = nextKeyIndex(i, len);
}
}
/**
* 删除节点后重新散列所有可能冲突的节点
* | key | value | key1 | value1 | key2 | value2 | -> | key1 | value1 | key2 | value2 | null | null |
* 该方法的实现较为混乱
* @param d 指定索引位置
*/
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) ) {
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;
}
}
}
/**
* 清空
*/
public void clear() {
modCount++;
Object[] tab = table;
for (int i = 0; i < tab.length; i++)
tab[i] = null;
size = 0;
}
/**
* 比较当前对象与指定对象是否相等
* @param o 指定对象
* @return 是否相等
*/
public boolean equals(Object o) {
if (o == this) {
return true;
} else if (o instanceof IdentityHashMap) {
IdentityHashMap<?,?> m = (IdentityHashMap<?,?>) o;
if (m.size() != size)
return false;
Object[] tab = m.table;
for (int i = 0; i < tab.length; i+=2) {
Object k = tab[i];
if (k != null && !containsMapping(k, tab[i + 1]))
return false;
}
return true;
} else if (o instanceof Map) {
Map<?,?> m = (Map<?,?>)o;
return entrySet().equals(m.entrySet());
} else {
return false; // o is not a Map
}
}
/**
* 获取哈希值
* @return 哈希值
*/
public int hashCode() {
int result = 0;
Object[] tab = table;
for (int i = 0; i < tab.length; i +=2) {
Object key = tab[i];
if (key != null) {
Object k = unmaskNull(key);
result += System.identityHashCode(k) ^
System.identityHashCode(tab[i + 1]);
}
}
return result;
}
/**
* 浅拷贝
* @return 克隆后的对象
*/
public Object clone() {
try {
IdentityHashMap<?,?> m = (IdentityHashMap<?,?>) super.clone();
m.entrySet = null;
m.table = table.clone();
return m;
} catch (CloneNotSupportedException e) {
throw new InternalError(e);
}
}
/**
* 迭代器
*/
private abstract class IdentityHashMapIterator<T> implements Iterator<T> {
//当前索引位置
int index = (size != 0 ? 0 : table.length);
//结构修改次数
int expectedModCount = modCount;
//移除节点前需要先获取当前索引位置,即先调用nextIndex后才能移除,下一次移除仍然需要先调用该方法
int lastReturnedIndex = -1;
//是否是有效索引
boolean indexValid; // To avoid unnecessary next computation
//哈希探针表
Object[] traversalTable = table; // reference to main table or copy
/**
* 从当前索引位置开始后续是否有下一个键
* @return 是否有下一个键
*/
public boolean hasNext() {
Object[] tab = traversalTable;
for (int i = index; i < tab.length; i+=2) {
Object key = tab[i];
if (key != null) {
index = i;
return indexValid = true;
}
}
index = tab.length;
return false;
}
/**
* 获取下一个索引
* @return 下一个索引
*/
protected int nextIndex() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
if (!indexValid && !hasNext())
throw new NoSuchElementException();
indexValid = false;
lastReturnedIndex = index;
index += 2;
return lastReturnedIndex;
}
/**
* 移除当前节点
*/
public void remove() {
if (lastReturnedIndex == -1)
throw new IllegalStateException();
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
expectedModCount = ++modCount;
int deletedSlot = lastReturnedIndex;
lastReturnedIndex = -1;
// back up index to revisit new contents after deletion
index = deletedSlot;
indexValid = false;
Object[] tab = traversalTable;
int len = tab.length;
int d = deletedSlot;
Object key = tab[d];
tab[d] = null; // vacate the slot
tab[d + 1] = null;
// If traversing a copy, remove in real table.
// We can skip gap-closure on copy.
if (tab != IdentityHashMap.this.table) {
IdentityHashMap.this.remove(key);
expectedModCount = modCount;
return;
}
size--;
//在删除节点后所有可能冲突的节点会被重新散列,但是遍历的索引确实不变的,这也就是导致了移动后的某些节点可能会遍历不到,所以它在变化前做了数组的拷贝以便能够正常访问
Object item;
for (int i = nextKeyIndex(d, len); (item = tab[i]) != null;
i = nextKeyIndex(i, len)) {
int r = hash(item, len);
// See closeDeletion for explanation of this conditional
if ((i < r && (r <= d || d <= i)) ||
(r <= d && d <= i)) {
if (i < deletedSlot && d >= deletedSlot &&
traversalTable == IdentityHashMap.this.table) {
int remaining = len - deletedSlot;
Object[] newTable = new Object[remaining];
System.arraycopy(tab, deletedSlot,
newTable, 0, remaining);
traversalTable = newTable;
index = 0;
}
tab[d] = item;
tab[d + 1] = tab[i + 1];
tab[i] = null;
tab[i + 1] = null;
d = i;
}
}
}
}
/**
* 包含所有键的迭代器
*/
private class KeyIterator extends IdentityHashMapIterator<K> {
@SuppressWarnings("unchecked")
public K next() {
return (K) unmaskNull(traversalTable[nextIndex()]);
}
}
/**
* 包含所有值的迭代器
*/
private class ValueIterator extends IdentityHashMapIterator<V> {
@SuppressWarnings("unchecked")
public V next() {
return (V) traversalTable[nextIndex() + 1];
}
}
/**
* 包含所有键值对的迭代器,都是类似的代码就不做解释了
*/
private class EntryIterator extends IdentityHashMapIterator<Map.Entry<K,V>> {
private Entry lastReturnedEntry;
public Map.Entry<K,V> next() {
lastReturnedEntry = new Entry(nextIndex());
return lastReturnedEntry;
}
public void remove() {
lastReturnedIndex =
((null == lastReturnedEntry) ? -1 : lastReturnedEntry.index);
super.remove();
lastReturnedEntry.index = lastReturnedIndex;
lastReturnedEntry = null;
}
private class Entry implements Map.Entry<K,V> {
private int index;
private Entry(int index) {
this.index = index;
}
@SuppressWarnings("unchecked")
public K getKey() {
checkIndexForEntryUse();
return (K) unmaskNull(traversalTable[index]);
}
@SuppressWarnings("unchecked")
public V getValue() {
checkIndexForEntryUse();
return (V) traversalTable[index+1];
}
@SuppressWarnings("unchecked")
public V setValue(V value) {
checkIndexForEntryUse();
V oldValue = (V) traversalTable[index+1];
traversalTable[index+1] = value;
// if shadowing, force into main table
if (traversalTable != IdentityHashMap.this.table)
put((K) traversalTable[index], value);
return oldValue;
}
public boolean equals(Object o) {
if (index < 0)
return super.equals(o);
if (!(o instanceof Map.Entry))
return false;
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
return (e.getKey() == unmaskNull(traversalTable[index]) &&
e.getValue() == traversalTable[index+1]);
}
public int hashCode() {
if (lastReturnedIndex < 0)
return super.hashCode();
return (System.identityHashCode(unmaskNull(traversalTable[index])) ^
System.identityHashCode(traversalTable[index+1]));
}
public String toString() {
if (index < 0)
return super.toString();
return (unmaskNull(traversalTable[index]) + "="
+ traversalTable[index+1]);
}
private void checkIndexForEntryUse() {
if (index < 0)
throw new IllegalStateException("Entry was removed");
}
}
}
/**
* 获取包含所有键的集合
* @return 包含所有键的Set集合
*/
public Set<K> keySet() {
Set<K> ks = keySet;
if (ks == null) {
ks = new KeySet();
keySet = ks;
}
return ks;
}
/**
* 包含哈希探针表中所有键的集合
*/
private class KeySet extends AbstractSet<K> {
public Iterator<K> iterator() {
return new KeyIterator();
}
public int size() {
return size;
}
public boolean contains(Object o) {
return containsKey(o);
}
public boolean remove(Object o) {
int oldSize = size;
IdentityHashMap.this.remove(o);
return size != oldSize;
}
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);
boolean modified = false;
for (Iterator<K> i = iterator(); i.hasNext(); ) {
if (c.contains(i.next())) {
i.remove();
modified = true;
}
}
return modified;
}
public void clear() {
IdentityHashMap.this.clear();
}
public int hashCode() {
int result = 0;
for (K key : this)
result += System.identityHashCode(key);
return result;
}
public Object[] toArray() {
return toArray(new Object[0]);
}
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
int expectedModCount = modCount;
int size = size();
if (a.length < size)
a = (T[]) Array.newInstance(a.getClass().getComponentType(), size);
Object[] tab = table;
int ti = 0;
for (int si = 0; si < tab.length; si += 2) {
Object key;
if ((key = tab[si]) != null) { // key present ?
// more elements than expected -> concurrent modification from other thread
if (ti >= size) {
throw new ConcurrentModificationException();
}
a[ti++] = (T) unmaskNull(key); // unmask key
}
}
// fewer elements than expected or concurrent modification from other thread detected
if (ti < size || expectedModCount != modCount) {
throw new ConcurrentModificationException();
}
// final null marker as per spec
if (ti < a.length) {
a[ti] = null;
}
return a;
}
public Spliterator<K> spliterator() {
return new KeySpliterator<>(IdentityHashMap.this, 0, -1, 0, 0);
}
}
/**
* 获取包含所有值的对象
* @return 包含所有值的对象
*/
public Collection<V> values() {
Collection<V> vs = values;
if (vs == null) {
vs = new Values();
values = vs;
}
return vs;
}
/**
* 包含所有值的对象
*/
private class Values extends AbstractCollection<V> {
public Iterator<V> iterator() {
return new ValueIterator();
}
public int size() {
return size;
}
public boolean contains(Object o) {
return containsValue(o);
}
public boolean remove(Object o) {
for (Iterator<V> i = iterator(); i.hasNext(); ) {
if (i.next() == o) {
i.remove();
return true;
}
}
return false;
}
public void clear() {
IdentityHashMap.this.clear();
}
public Object[] toArray() {
return toArray(new Object[0]);
}
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
int expectedModCount = modCount;
int size = size();
if (a.length < size)
a = (T[]) Array.newInstance(a.getClass().getComponentType(), size);
Object[] tab = table;
int ti = 0;
for (int si = 0; si < tab.length; si += 2) {
if (tab[si] != null) { // key present ?
// more elements than expected -> concurrent modification from other thread
if (ti >= size) {
throw new ConcurrentModificationException();
}
a[ti++] = (T) tab[si+1]; // copy value
}
}
// fewer elements than expected or concurrent modification from other thread detected
if (ti < size || expectedModCount != modCount) {
throw new ConcurrentModificationException();
}
// final null marker as per spec
if (ti < a.length) {
a[ti] = null;
}
return a;
}
public Spliterator<V> spliterator() {
return new ValueSpliterator<>(IdentityHashMap.this, 0, -1, 0, 0);
}
}
/**
* 获取包含所有键值对的集合
* @return 包含所有键值对的集合
*/
public Set<Map.Entry<K,V>> entrySet() {
Set<Map.Entry<K,V>> es = entrySet;
if (es != null)
return es;
else
return entrySet = new EntrySet();
}
/**
* 包含所有键值对的集合
*/
private class EntrySet extends AbstractSet<Map.Entry<K,V>> {
public Iterator<Map.Entry<K,V>> iterator() {
return new EntryIterator();
}
public boolean contains(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry<?,?> entry = (Map.Entry<?,?>)o;
return containsMapping(entry.getKey(), entry.getValue());
}
public boolean remove(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry<?,?> entry = (Map.Entry<?,?>)o;
return removeMapping(entry.getKey(), entry.getValue());
}
public int size() {
return size;
}
public void clear() {
IdentityHashMap.this.clear();
}
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);
boolean modified = false;
for (Iterator<Map.Entry<K,V>> i = iterator(); i.hasNext(); ) {
if (c.contains(i.next())) {
i.remove();
modified = true;
}
}
return modified;
}
public Object[] toArray() {
return toArray(new Object[0]);
}
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
int expectedModCount = modCount;
int size = size();
if (a.length < size)
a = (T[]) Array.newInstance(a.getClass().getComponentType(), size);
Object[] tab = table;
int ti = 0;
for (int si = 0; si < tab.length; si += 2) {
Object key;
if ((key = tab[si]) != null) { // key present ?
// more elements than expected -> concurrent modification from other thread
if (ti >= size) {
throw new ConcurrentModificationException();
}
a[ti++] = (T) new AbstractMap.SimpleEntry<>(unmaskNull(key), tab[si + 1]);
}
}
// fewer elements than expected or concurrent modification from other thread detected
if (ti < size || expectedModCount != modCount) {
throw new ConcurrentModificationException();
}
// final null marker as per spec
if (ti < a.length) {
a[ti] = null;
}
return a;
}
public Spliterator<Map.Entry<K,V>> spliterator() {
return new EntrySpliterator<>(IdentityHashMap.this, 0, -1, 0, 0);
}
}
/**
* 自定义序列化
* @param s 输出流
*/
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {
// Write out and any hidden stuff
s.defaultWriteObject();
// Write out size (number of Mappings)
s.writeInt(size);
// Write out keys and values (alternating)
Object[] tab = table;
for (int i = 0; i < tab.length; i += 2) {
Object key = tab[i];
if (key != null) {
s.writeObject(unmaskNull(key));
s.writeObject(tab[i + 1]);
}
}
}
/**
* 自定义反序列化
* @param s 输入流
*/
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
// Read in any hidden stuff
s.defaultReadObject();
// Read in size (number of Mappings)
int size = s.readInt();
if (size < 0)
throw new java.io.StreamCorruptedException
("Illegal mappings count: " + size);
int cap = capacity(size);
SharedSecrets.getJavaOISAccess().checkArray(s, Object[].class, cap);
init(cap);
// Read the keys and values, and put the mappings in the table
for (int i=0; i<size; i++) {
@SuppressWarnings("unchecked")
K key = (K) s.readObject();
@SuppressWarnings("unchecked")
V value = (V) s.readObject();
putForCreate(key, value);
}
}
/**
* 反序列化时将键值对存储到哈希探针表上
* @param key 指定键
* @param value 指定值
*/
private void putForCreate(K key, V value) throws java.io.StreamCorruptedException {
Object k = maskNull(key);
Object[] tab = table;
int len = tab.length;
int i = hash(k, len);
Object item;
while ( (item = tab[i]) != null) {
if (item == k)
throw new java.io.StreamCorruptedException();
i = nextKeyIndex(i, len);
}
tab[i] = k;
tab[i + 1] = value;
}
/**
* 遍历哈希探针表并执行指定动作
* @param action 指定动作
*/
@SuppressWarnings("unchecked")
@Override
public void forEach(BiConsumer<? super K, ? super V> action) {
Objects.requireNonNull(action);
int expectedModCount = modCount;
Object[] t = table;
for (int index = 0; index < t.length; index += 2) {
Object k = t[index];
if (k != null) {
action.accept((K) unmaskNull(k), (V) t[index + 1]);
}
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
}
/**
* 遍历哈希探针表并执行指定动作后获取新值,利用新值替换所有节点的旧值
* @param function 指定动作
*/
@SuppressWarnings("unchecked")
@Override
public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
Objects.requireNonNull(function);
int expectedModCount = modCount;
Object[] t = table;
for (int index = 0; index < t.length; index += 2) {
Object k = t[index];
if (k != null) {
t[index + 1] = function.apply((K) unmaskNull(k), (V) t[index + 1]);
}
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
}
添加节点
/**
* 添加节点
* 先获取偶数索引位置,若该位置上已经存在节点且两者的节点相等,则进行替换,若两者的节点不相等则继续往下查找偶数索引位置,直到偶数位置上不存在节点时才跳出循环
* 在上面我们提到,在最大键值对中必须有一个地方存在null,否则会陷入死循环,而这里正好也是说明了这一点,要是在最大键值对中所有的偶数位置上都已经填充了节点,那么它会一直查找,陷入了一个环形的查找中,反正就是死循环了
* @param key 指定键
* @param value 指定值
* @return null或旧值
*/
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) { //若新增的节点与当前偶数索引位置上的节点相等,将新值替换旧值
@SuppressWarnings("unchecked")
V oldValue = (V) tab[i + 1];
tab[i + 1] = value;
return oldValue;
}
}
final int s = size + 1;
/**
* s + (s << 1) -> 3 * s
* 添加节点后是否超过容量的1/3,若超过则进行扩容,扩容成功后要在新表中重新查找偶数索引位置,若扩容失败或不需要扩容则直接存储节点
*/
if (s + (s << 1) > len && resize(len))
continue retryAfterResize; //代码又回到for循环上
modCount++;
tab[i] = k;
tab[i + 1] = value;
size = s;
return null;
}
}
/**
* 添加指定集合到线性探针表中
* @param m 指定集合
*/
public void putAll(Map<? extends K, ? extends V> m) {
int n = m.size();
if (n == 0)
return;
if (n > size)
resize(capacity(n)); //保守扩容
for (Entry<? extends K, ? extends V> e : m.entrySet())
put(e.getKey(), e.getValue());
}
获取节点
/**
* 通过指定键获取值
* @param key 指定键
* @return null或值
*/
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];
if (item == null)
return null;
i = nextKeyIndex(i, len);
}
}
移除节点
/**
* 通过指定键移除节点
* 移除节点后会重新散列所有可能冲突的节点
* @param key 指定键
* @return null或旧值
*/
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--;
@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);
}
}
/**
* 通过键值对移除节点
* @param key 指定键
* @param value 指定值
* @return 是否移除成功
*/
private boolean removeMapping(Object key, Object value) {
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) {
if (tab[i + 1] != value)
return false;
modCount++;
size--;
tab[i] = null;
tab[i + 1] = null;
closeDeletion(i);
return true;
}
if (item == null)
return false;
i = nextKeyIndex(i, len);
}
}
总结
-
IdentityHashMap的数据结构是
线性探针表。 -
IdentityHashMap采用的是
引用相等,而HashMap采用的是对象相等。 -
IdentityHashMap默认容量大小是64,个人认为加载因子是1/3。
-
IdentityHashMap的容量大小必须是2的幂次方。
-
IdentityHashMap用于序列化或深拷贝、代理场景中,不过即使这么说,我还是没能感受到它的用处。
-
IdentityHashMap无序、不可重复、非线程安全。
-
IdentityHashMap的键值对允许存放null。
-
添加节点流程:首先获取索引位置,接着若发现当前位置上不存在节点则直接添加皆可,若发现当前位置上已经存在节点了则比较两者是否相等(采用 k1 == k2的方式),若相等则说明重复进行替换值即可,若不相等说明发生冲突,它会往后查抄偶数索引位置,直到发现偶数索引位置上不存在节点时才进行存储。 -
扩容机制:在添加元素时判断当前节点个数是否超过了容量的1/3,若超过则以2倍大小进行扩容,扩容时对哈希探针表中的所有节点进行重新散列,扩容结束后从重新走上面的添加节点流程,因为节点的索引位置已经发生变化;最大键值对是 1 << 29,最小键值对是 4,虽说最大键值对是1 << 29,但实际上能存储的最大键值对是 1 << 29 -1,因为它要保留一个null来防止死循环,在程序中它采用的是不断遍历哈希探针表来获取偶数位置上不存在节点的索引,若所有位置上都填充了节点,就会陷入死循环中,所以至少要有这样子的一个null。 -
删除节点流程:在删除节点后,它会重新散列所有可能冲突的节点。按照上面的添加节点流程中我们知道,两个节点即使发生冲突了也只是找其他的位置进行存储,这和不冲突的情况下进行存储并没有什么区别,所以在删除节点后,它会重新散列所有节点。
重点关注
resize put remove
浙公网安备 33010602011771号