??IdentityHashMap利用哈希表實(shí)現(xiàn)Map接口港令,不同的是,其比較鍵(或值)時(shí)锈颗,使用引用相等性代替對(duì)象相等性顷霹。換句話說,在IdentityHashMap中击吱,當(dāng)且僅當(dāng)k1==k2時(shí)淋淀,才認(rèn)為兩個(gè)鍵相等;而在正常的Map實(shí)現(xiàn)中(比如HashMap)姨拥,當(dāng)且僅當(dāng)兩個(gè)鍵k1和K2滿足:k1==null?k2==null:k1.equals(k2)時(shí)绅喉,兩個(gè)鍵才相等渠鸽。
??此類不是通用的Map實(shí)現(xiàn)叫乌,實(shí)現(xiàn)Map接口的常規(guī)協(xié)定是比較對(duì)象時(shí)使用equals方法柴罐。而IdentityHashMap不是,此類設(shè)計(jì)僅用于需要引用相等性語(yǔ)義的情形憨奸。此類提供所有的可選映射操作革屠,并且允許 null 值和 null 鍵。此類對(duì)映射的順序不提供任何保證排宰;特別是不保證順序隨時(shí)間的推移保持不變似芝。
主要看下put和get方法的實(shí)現(xiàn):
public V put(K key, V value) {
//判斷key是否為空
final Object k = maskNull(key);
retryAfterResize: for (;;) {
final Object[] tab = table;
final int len = tab.length;
//根據(jù)key和哈希表長(zhǎng)度計(jì)算哈希值
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;
//當(dāng)該key存在時(shí),返回舊值
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;
//當(dāng)該key不存在時(shí)板甘,返回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);
}
}
對(duì)比HashMap的put和get實(shí)現(xiàn):
//put方法實(shí)現(xiàn)
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;
//判斷哈希表是否為空党瓮,若為空,進(jìn)行初始化
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//根據(jù)key的哈希值計(jì)算key在哈希表中的存儲(chǔ)位置
if ((p = tab[i = (n - 1) & hash]) == null)
//該位置為空盐类,新建一個(gè)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方法實(shí)現(xiàn)
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的實(shí)現(xiàn)中可以看出IdentityHashMap和通用Map的區(qū)別,IdentityHashMap比較key時(shí)使用引用相等性(==)在跳,而通用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不是線程安全的,當(dāng)多線程同時(shí)修改IdentityHashMap時(shí)猫妙,必須外部保持同步瓷翻。