IdentityHashMap类与HashMap相似,不同之处在于它在比较元素时使用引用相等性。此类不是通用Map实现。虽然此类实现Map接口,但它有意违反Map的常规协定,后者要求在比较对象时使用equals方法。
以下是IdentityHashMap类的一些方法-
序号 | 方法与说明 |
---|---|
1 | voidclear() 从此映射中删除所有映射。 |
2 | Objectclone() 返回此标识哈希映射的浅表副本:键和值本身不会被克隆。 |
3 | boolean containsKey(Object key) 测试指定的对象引用是否是此标识哈希映射中的键。 |
4 | boolean containsValue(Object value) 测试指定的对象引用是否是此标识哈希映射中的值。 |
5 | SetentrySet() 返回此映射中包含的映射的设置视图。 |
6 | boolean equals(Object o) 比较指定对象与此映射是否相等。 |
7 | Object get(Object key) 返回此标识哈希映射中指定键所映射到的值;如果该映射不包含此键的映射关系,则返回null。 |
8 | inthashCode() 返回此映射的哈希码值。 |
以下是在Java中实现IdentityHashMap类的示例-
import java.util.*; public class Main { public static void main(String args[]) { IdentityHashMap iHashMap = new IdentityHashMap(); iHashMap.put("John", new Integer(10000)); iHashMap.put("Tim", new Integer(25000)); iHashMap.put("Adam", new Integer(15000)); iHashMap.put("Katie", new Integer(30000)); iHashMap.put("Jacob", new Integer(45000)); iHashMap.put("Steve", new Integer(23000)); iHashMap.put("Nathan", new Integer(25000)); iHashMap.put("Amy", new Integer(27000)); Set set = iHashMap.entrySet(); Iterator iterator = set.iterator(); while(iterator.hasNext()) { Map.Entry map = (Map.Entry)iterator.next(); System.out.print(map.getKey() + ": "); System.out.println(map.getValue()); } System.out.println(); System.out.println("Size of IdentintyHashMap: "+iHashMap.size()); int bonus = ((Integer)iHashMap.get("Amy")).intValue(); iHashMap.put("Amy", new Integer(bonus + 5000)); System.out.println("Amy's salary after bonus = " + iHashMap.get("Amy")); int deductions = ((Integer)iHashMap.get("Steve")).intValue(); iHashMap.put("Steve", new Integer(deductions - 3000)); System.out.println("Steve's salary after deductions = " + iHashMap.get("Steve")); } }
输出结果
Steve: 23000 Adam: 15000 Katie: 30000 Nathan: 25000 Tim: 25000 Amy: 27000 John: 10000 Jacob: 45000 Size of IdentintyHashMap: 8 Amy's salary after bonus = 32000 Steve's salary after deductions = 20000