A typical use of this class is
topology-preserving object graph
transformations, such as serialization
or deep-copying. To perform such a
transformation, a program must
maintain a "node table" that keeps
track of all the object references
that have already been processed. The
node table must not equate distinct
objects even if they happen to be
equal. 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<Object, String> m = new IdentityHashMap<>();
// Any keys, we keep their references
Object[] keys = { "strkey", new Object(), new Integer(1234567) };
for (int i = 0; i < keys.length; i++)
m.put(keys[i], "Key #" + i);
// We query values from map by the same references:
for (Object key : keys)
System.out.println(key + ": " + m.get(key));
# 1 楼答案
这是我的一次实践经验:
对于大型基数,IdentityHashMap比HashMap留下的内存占用要小得多
# 2 楼答案
如果键是类对象,则可以使用IdentityHashMap。这比gets的HashMap快33%左右!它可能也会占用更少的内存
# 3 楼答案
HashMap在每次添加对象时都会创建条目对象,这会在有很多对象时给GC带来很大压力。在一个包含1000个或更多对象的HashMap中,您最终会使用相当大一部分CPU,而只是拥有GC清理条目(在诸如寻路或其他创建并清理的一次性集合的情况下)。IdentityHashMap没有这个问题,所以最终会大大加快速度
请参见此处的基准:http://www.javagaming.org/index.php/topic,21395.0/topicseen.html
# 4 楼答案
无论何时,只要您不希望通过
equals
而希望通过==
比较密钥,就可以使用IdentityHashMap。如果你正在做大量的参考处理,但它仅限于非常特殊的情况,这可能非常有用# 5 楼答案
报告说:
# 6 楼答案
您还可以将
IdentityHashMap
用作通用地图如果您可以确保用作关键帧的对象将是相等的当且仅当它们的引用相等时有什么好处?显然,与使用
HashMap
或TreeMap
等实现相比,它将更快,并且使用更少的内存事实上,这种情况在很多情况下都存在。例如:
Enum
s。尽管对于enum还有更好的选择:^{Class
对象。它们在参考方面也具有可比性李>String.intern()
李>演示最后一点:
输出将如预期的那样(因为我们使用相同的
Object
引用从映射中查询值):