【JDK1.8】JDK1.8集合源码阅读——IdentityHashMap

今天我们来看一下本次集合源码阅读里的最后一个Map——IdentityHashMap。这个Map之所以放在最后是因为它用到的情况最少,也相较于其他的map来说比较特殊。就笔者来说,到目前为止还没有用到过它 ┐(゚~゚)┌。它的罕见与它的用途有关,当时的Map设计者是这么说的:

This class is designed for use only in the rare cases wherein reference-equality semantics are required.

这个类仅用于需要引用相等的罕见情况。

A typical use of this class is topology-preserving object graph transformations, such as serialization or deep-copying.

该类一个典型的用途是拓扑保存对象图的转换,比如序列化或者深度拷贝

Another typical use of this class is to maintain proxy objects. For example, a debugging facility might wish to maintain a proxy object for each object in the program being debugged.

这个类的另一个典型用途是维护代理对象。 例如,调试工具可能希望为正在调试的程序中的每个对象维护一个代理对象

上面提到,这个Map采用的是引用相等的情况,即内存地址相同。我们来看一下它用法:

public static void main(String[] args) { IdentityHashMap<String, Integer> map = new IdentityHashMap<>(); map.put("Hello " + "World", 1); map.put("Hello World", 2); map.put(new String("Hello World"), 3); map.put(null, 4); map.put(null, 5); System.out.println(map); }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zydxfp.html