-1

I'm maintaining a piece of software that is using an IdentityHashMap to store a list of objects as the key, but I noticed that everywhere in the code just populates the paired value with null and nothing ever seems to reference the value either. This feels wrong to me, I don't know why a map is being used when the value being stored is effectively ignored.

Based on my observations, the map key is being used to store/compare objects and the previous author is using contains before populating the map to make sure no attempts to add duplicate objects are made.

I'm not familiar with all the different data structures in Java, but I'm guessing a collection is better suited for this purpose. I came to HashSet because the order doesn't matter and we don't want duplicates.

Where you guys come in is I'm wondering if my thought process is correct. Is there perhaps something I may not be considering as to why the original author went with IdentityHashMap? Would HashSet be the appropriate alternative where the value pairings are not required? Are there any performance considerations? (eg. is IdentityHashMap actually faster than a HashSet in this context?)

If HashSet isn't the correct data structure, what is?

4

2 回答 2

5

IdentityHashMap用于==确定两个对象是否相同,而HashSet使用equals.

如果您想要 a与 aSet具有相同的语义IdentityHashMap,您可能希望查看Collections.newSetFromMap.

Set<T> identityHashSet = Collections.newSetFromMap(new IdentityHashMap<T, Boolean>());
于 2012-12-20T02:04:15.850 回答
2

在此处使用 aHashSet会提供不同的行为。听起来好像IdentityHashMap是用于检查地图中是否存在具有相同标识的对象。如果您使用 a HashSet,则该contains方法用于equals比较(其中 asIdentityHashMap使用==)。

在不了解该问题的情况下,我无法推测为什么要这样做,但要回答您的问题, aHashSet不会是等效的替代品。

如果您想使用一个集合,因为使用带有空值的映射似乎不正确(看起来确实有点不干净),请考虑将对象包装在identity equivalence中。然后他们的equals方法将委托给==.

于 2012-12-20T02:05:13.710 回答