Java 集合框架
IdentityHashMap实现Map,Serializable和Clonable接口并扩展AbstractMap类。
这个类不是一个通用的Map实现。虽然这个类实现了Map接口,但它有意违反了Map的通用契约,它在比较对象时要求使用equals方法。当用户需要通过引用比较对象时使用此类。
构造函数
IdentityHashMap():构造一个具有默认预期最大大小的新的空白身份哈希映射。
IdentityHashMap(int expectedMaxSize):用指定的预期最大大小构造一个新的空映射。
IdentityHashMap(Map m):构造一个新的标识哈希映射,其中包含指定映射中的键 - 值映射。
IdentityHashMap的方法
clear() - 从此映射中删除所有映射。
clone()- 返回此身份哈希映射的浅表副本:键和值本身未被克隆。
containsKey(Object key) - 如果此映射包含指定键的映射关系,则返回true。
containsValue(Object value) - 如果此映射将一个或多个键映射到指定值,则返回true。
entrySet() - 返回此映射中包含的映射的Set视图。
equals(Object o)- 将指定对象与此映射进行比较以获得相等性。
get(Object key)- 返回指定键映射到的值;如果此映射不包含键映射,则返回null。
hashCode()- 返回此映射的哈希码值。
isEmpty()- 如果此映射不包含键值映射,则返回true。
keySet() - 返回包含在此映射中的键的Set视图。
put(K key,V value) - 将指定的值与该映射中指定的键相关联。
putAll(Map m) - 将指定映射中的所有映射复制到此映射。
remove(Object key)- 从弱哈希映射中删除密钥的映射(如果存在)。
size() - 返回此映射中键值映射的数量。
values()- 返回此映射中包含的值的Collection。
IdentityHashMap vs HashMap
IdentityHashMap使用相等运算符“==”来比较键和值,而HashMap使用equals方法来比较Map中的键和值。
由于IdentityHashMap不使用equals(),因此对于具有比较费时,昂贵的equals()的对象,它的速度比HashMap快。
IdentityHashMap不要求密钥不可变,因为它不依赖于equals()。
IdentityHashMap 执行示例
// Java code to demonstrate IdentityHashMap and
// illustration of how it is different from HashMap
import java.util.Map;
import java.util.HashMap;
import java.util.IdentityHashMap;
public class IdentityHashMapExample
{
public static void main(String[] args)
{
// Creating HashMap and IdentityHashMap objects
Map hm = new HashMap();
Map ihm = new IdentityHashMap();
// Putting key and value in HashMap and IdentityHashMap Object
hm.put("hmkey","hmvalue");
hm.put(new String("hmkey"),"hmvalue1");
ihm.put("ihmkey","ihmvalue");
ihm.put(new String("ihmkey"),"ihmvalue1");
// Print Size of HashMap and WeakHashMap Object
//hm.size() will print 1 since it compares the objects logically
// and both the keys are same
System.out.println("Size of HashMap--"+hm.size());
//ihm.size() will print 2 since it compares the objects by reference
System.out.println("Size of IdentityHashMap--"+ihm.size());
}
}
输出:
Size of HashMap--1
Size of IdentityHashMap--2