IdentityHashMap利用哈希表实现Map接口,不同的是,其比较键(或值)时,使用引用相等性代替对象相等性。换句话说,在IdentityHashMap中,当且仅当k1==k2时,才认为两个键相等;而在正常的Map实现中(比如HashMap),当且仅当两个键k1和K2满足:k1==null?k2==null:k1.equals(k2)时,两个键才相等。
此类不是通用的Map实现,实现Map接口的常规协定是比较对象时使用equals方法。而IdentityHashMap不是,此类设计仅用于需要引用相等性语义的情形。此类提供所有的可选映射操作,并且允许 null 值和 null 键。此类对映射的顺序不提供任何保证;特别是不保证顺序随时间的推移保持不变。
主要看下put和get方法的实现:
public V put(K key, V value) {
//判断key是否为空
final Object k = maskNull(key);
retryAfterResize: for (;;) {
final Object[] tab = table;
final int len = tab.length;
//根据key和哈希表长度计算哈希值
int i = hash(k, len);
for (Object item; (item = tab[i]) != null;
i = nextKeyIndex(i, len)) {
//引用比较key的值
if (item == k) {
@SuppressWarnings("unchecked")
V oldValue = (V) tab[i + 1];
tab[i + 1] = value;
//当该key存在时,返回旧值
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;
//当该key不存在时,返回null
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];
//引用比较key的值
if (item == k)
return (V) tab[i + 1];
if (item == null)
return null;
i = nextKeyIndex(i, len);
}
}
对比HashMap的put和get实现:
//put方法实现
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
//判断哈希表是否为空,若为空,进行初始化
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//根据key的哈希值计算key在哈希表中的存储位置
if ((p = tab[i = (n - 1) & hash]) == null)
//该位置为空,新建一个node,存入哈希表(tab[i])
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
//比较key
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
//get方法实现
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
从上面的put和get的实现中可以看出IdentityHashMap和通用Map的区别,IdentityHashMap比较key时使用引用相等性(==),而通用Map比较key还使用equals方法。
举例:
public class Person {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id=id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name=name;
}
public Person() {}
public Person(String id,String name) {
super();
this.id=id;
this.name=name;
}
public String toString() {
return "Person[id="+id+",name="+name+"]";
}
//重写equals方法
public boolean equals(Object object) {
if(object instanceof Person) {
Person person=(Person)object;
return Objects.equal(this.id,person.getId());
}
return false;
}
public int hashCode() {
return this.id.hashCode();
}
}
import java.util.HashMap;
import java.util.IdentityHashMap;
public class MainDemo {
public static void main(String args[]) {
IdentityHashMap<Student,String> imap=new IdentityHashMap<>();
HashMap<Student,String> map=new HashMap<>();
Student s1=new Student("1","whisper");
Student s2=new Student("1","whisper");
map.put(s1, "whisper");
map.put(s2, "godyan");
imap.put(s1, "whisper");
imap.put(s2, "godyan");
System.out.println("map.size()="+map.size()+",map.get(s1)="+map.get(s1)+",map.get(s2)="+map.get(s2));
System.out.println("---------------------------------------------");
System.out.println("imap.size()="+imap.size()+",imap.get(s1)="+imap.get(s1)+",imap.get(s2)="+imap.get(s2));
}
}
输出:
map.size()=1,map.get(s1)=godyan,map.get(s2)=godyan
---------------------------------------------
imap.size()=2,imap.get(s1)=whisper,imap.get(s2)=godyan
注意:Identity不是线程安全的,当多线程同时修改IdentityHashMap时,必须外部保持同步。