此类利用哈希表实现 Map 接口,比较键(和值)时使用引用相等性代替对象相等性。换句话说,在 IdentityHashMap 中,当且仅当 (k1==k2) 时,才认为两个键 k1 和 k2 相等(在正常 Map 实现(如 HashMap)中,当且仅当满足下列条件时才认为两个键 k1 和 k2 相等:(k1==null ? k2==null : e1.equals(e2)))。
此类不是 通用 Map 实现!此类实现 Map 接口时,它有意违反 Map 的常规协定,该协定在比较对象时强制使用 equals 方法。此类设计仅用于其中需要引用相等性语义的罕见情况。
例子一 :
IdentityHashMap<String,Object> map =newIdentityHashMap<String,Object>();
map.put(newString("xx"),"first");
map.put(newString("xx"),"second");
for (Entry<String, Object> entry : map.entrySet()) {
System.out.print(entry.getKey() +" ");
System.out.println(entry.getValue());
}
System.out.println("idenMap="+map.containsKey("xx"));
System.out.println("idenMap="+map.get("xx"));
输入结果是:
xx first
xx second
idenMap=false
idenMap=null
解释下第三行输出: "xx"字符串常量是在常量池中的, 而map中的键值对的键是一个String对象,两者的地址不相等
例子二:
IdentityHashMap<String,Object> map =newIdentityHashMap<String,Object>();
String fsString =newString("xx");
map.put(fsString,"first");
map.put(newString("xx"),"second");
for(Entry<String, Object> entry : map.entrySet()) {
System.out.print(entry.getKey() +" ");
System.out.println(entry.getValue());
}
System.out.println("idenMap="+map.containsKey(fsString));
System.out.println("idenMap="+map.get(fsString));
输出结果是:
[plain] view plain copy
xx second
xx first
idenMap=true
idenMap=first
例子三:
IdentityHashMap<String,Object> map =newIdentityHashMap<String,Object>();
String fsString =newString("xx");
map.put(fsString,"first");
map.put(fsString,"second");
for(Entry<String, Object> entry : map.entrySet()) {
System.out.print(entry.getKey() +" ");
System.out.println(entry.getValue());
}
System.out.println("idenMap="+map.containsKey(fsString));
System.out.println("idenMap="+map.get(fsString));
输出结果是:
[plain] view plain copy
xx second
idenMap=true
idenMap=second
例子四;
IdentityHashMap<String,Object> map =newIdentityHashMap<String,Object>();
String fsString =newString("xx");
String secString =newString("xx");
map.put(fsString,"first");
map.put(secString,"second");
for(Entry<String, Object> entry : map.entrySet()) {
System.out.print(entry.getKey() +" ");
System.out.println(entry.getValue());
}
System.out.println("idenMap="+map.containsKey(fsString));
System.out.println("idenMap="+map.get(fsString));
System.out.println("idenMap="+map.containsKey(secString));
System.out.println("idenMap="+map.get(secString));
输出结果是:
[plain] view plain copy
xx first
xx second
idenMap=true
idenMap=first
idenMap=true
idenMap=second