在这篇文章中,我们将讨论来自java.util package的IdentityHashMap。
这个类不是一个通用的Map实现! 虽然该类实现了Map接口,但是它故意违反了Map的一般契约,该契约规定在比较对象时必须使用等价方法。该类仅设计用于需要引用平等语义的少数情况。
IdentityHashMap是Map接口的基于HashTable的实现。接口。普通的HashMap使用'.equals'方法对键进行比较。但是IdentityHashMap使用'=='操作符来比较其键值。
注意,这个实现是不同步的。如果多个线程同时访问一个IdentityHashMap,并且至少有一个线程在结构上修改了该图,那么它必须在外部进行同步。
举例来说。
Map m = Collections.synchronizedMap(new IdentityHashMap(...));
正如我们所知,IdentityHashMap是一个基于HashTable的Map接口的实现。接口。普通的HashMap使用'.equals'方法对键进行比较。但是IdentityHashMap使用'=='操作符比较其键值。因此,'a'和new String('a')被认为是两个不同的键。IdentityHashMap的初始大小为21,而正常HashMap的初始大小为16。
import java.util.IdentityHashMap;
public class IdentityHashMapExample {
public static void main(final String[] args) {
final IdentityHashMap<String, String> identityHashMap = new IdentityHashMap<String, String>();
identityHashMap.put("a", "Java");
identityHashMap.put(new String("a"), "J2EE");
identityHashMap.put("b", "J2SE");
identityHashMap.put(new String("b"), "Spring");
identityHashMap.put("c", "Hibernate");
for (final String str : identityHashMap.keySet()) {
System.out.println("Key : " + str + " and Value : " + identityHashMap.get(str));
}
System.out.println("Size of map is : " + identityHashMap.size());
System.out.println("Here 'a' and new String('a') are considered as separate keys");
}
}
输出:
Key : a and Value : Java
Key : b and Value : J2SE
Key : c and Value : Hibernate
Key : b and Value : Spring
Key : a and Value : J2EE
Size of map is : 5
Here 'a' and new String('a') are considered as separate keys
。
###参考资料
https://docs.oracle.com/javase/8/docs/api/java/util/IdentityHashMap.html
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.javaguides.net/2018/08/identityhashmap-in-java.html
内容来源于网络,如有侵权,请联系作者删除!