在Java中,有一種key值可以重復的map,就是IdentityHashMap。在IdentityHashMap中,判斷兩個鍵值k1和 k2相等的條件是 k1 == k2 。在正常的Map 實現(如 HashMap)中,當且僅當滿足下列條件時才認為兩個鍵 k1 和 k2 相等:(k1==null ? k2==null : e1.equals(e2))。
IdentityHashMap類利用哈希表實現 Map 接口,比較鍵(和值)時使用引用相等性代替對象相等性。該類不是 通用 Map 實現!此類實現 Map 接口時,它有意違反 Map 的常規協定,該協定在比較對象時強制使用 equals 方法。此類設計僅用於其中需要引用相等性語義的罕見情況。
具體說明,詳見:http://download.oracle.com/javase/6/docs/api/java/util/IdentityHashMap.html
http://www.cjsdn.net/Doc/JDK50/java/util/IdentityHashMap.html
在使用IdentityHashMap有些需要注意的地方:
例子1:
IdentityHashMap<String,Object> map =new IdentityHashMap<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
例子2:
IdentityHashMap<String,Object> map =new IdentityHashMap<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));
輸出結果是:
xx second xx first idenMap=true idenMap=first
例子3:
IdentityHashMap<String,Object> map =new IdentityHashMap<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));
輸出結果是:
xx second idenMap=true idenMap=second
例子4:
IdentityHashMap<String,Object> map =new IdentityHashMap<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));
輸出結果是:
xx first xx second idenMap=true idenMap=first idenMap=true idenMap=second
例子5:
IdentityHashMap<String,Object> map =new IdentityHashMap<String,Object>();
map.put("xx","first");
map.put("xx","second");
for(Entry<String, Object> entry : map.entrySet()) {
System.out.print(entry.getKey() +" ");
System.out.println(entry.getValue());
}
輸出結果是:
xx second
可以看到,在IdentityHashMap中,是判斷key是否為同一個對象,而不是普通HashMap的equals方式判斷。
參考:http://blog.csdn.net/stoneok07/article/details/7262676
