java map 允许重复_java中key值可以重复的map:IdentityHashMap
在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 方法。此類設計僅用于其中需要引用相等性語義的罕見情況。
在使用IdentityHashMap有些需要注意的地方:
例子1:
IdentityHashMap map =new IdentityHashMap();
map.put(newString("xx"),"first");
map.put(newString("xx"),"second");
for (Entry 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 map =new IdentityHashMap();
String fsString =newString("xx");
map.put(fsString,"first");
map.put(newString("xx"),"second");
for(Entry 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 map =new IdentityHashMap();
String fsString =newString("xx");
map.put(fsString,"first");
map.put(fsString,"second");
for(Entry 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 map =new IdentityHashMap();
String fsString =newString("xx");
String secString =newString("xx");
map.put(fsString,"first");
map.put(secString,"second");
for(Entry 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 map =new IdentityHashMap();
map.put("xx","first");
map.put("xx","second");
for(Entry 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
總結
以上是生活随笔為你收集整理的java map 允许重复_java中key值可以重复的map:IdentityHashMap的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 编程应该用 Mac ,还是 PC ?
- 下一篇: 取消计算机触摸板,笔记本电脑触摸板如何打