[英]object reference set in java
I need to create a Set of objects. 我需要创建一组对象。 The concern is I do not want to base the hashing or the equality on the objects' hashCode and equals implementation.
我担心的是,我不想将哈希或等式基于对象的hashCode和equals实现。 Instead, I want the hash code and equality to be based only on each object's reference identity (ie: the value of the reference pointer).
相反,我希望哈希码和相等性仅基于每个对象的引用标识(即:引用指针的值)。
I'm not sure how to do this in Java. 我不确定如何在Java中执行此操作。
The reasoning behind this is my objects do not reliably implement equals or hashCode, and in this case reference identity is good enough. 这背后的原因是我的对象无法可靠地实现equals或hashCode,在这种情况下,引用标识就足够了。
I guess that java.util.IdentityHashMap
is what you're looking for (note, there's no IdentityHashSet
). 我想您正在寻找
java.util.IdentityHashMap
(请注意,没有IdentityHashSet
)。 Lookup the API documentation: 查找API文档:
This class implements the
Map
interface with a hash table, using reference-equality in place of object-equality when comparing keys (and values).此类使用哈希表实现
Map
接口,在比较键(和值)时使用引用相等代替对象相等。 In other words, in anIdentityHashMap
, two keysk1
andk2
are considered equal if and only if(k1==k2)
.换句话说,在
IdentityHashMap
,当且仅当(k1==k2)
,两个键k1
和k2
被视为相等。 (In normalMap
implementations (likeHashMap
) two keysk1
andk2
are considered equal if and only if(k1==null ? k2==null : k1.equals(k2))
.)(在普通
Map
实现中(如HashMap
),只有且仅当(k1==null ? k2==null : k1.equals(k2))
两个键k1
和k2
才被视为相等。)This class is not a general-purpose
Map
implementation!此类不是通用的
Map
实现! While this class implements theMap
interface, it intentionally violatesMap
's general contract, which mandates the use of theequals
method when comparing objects.虽然此类实现
Map
接口,但它有意违反Map
的常规协定,该协定要求在比较对象时使用equals
方法。 This class is designed for use only in the rare cases wherein reference-equality semantics are required.此类仅设计用于仅在需要引用相等语义的情况下使用。
edit : See Joachim Sauer's comment below, it's really easy to make a Set
based on a certain Map
. 编辑 :请参阅下面的Joachim Sauer的评论,基于特定
Map
制作Set
真的很容易。 You'd need to do something like this: 您需要执行以下操作:
Set<E> mySet = Collections.newSetFromMap(new IdentityHashMap<E, Boolean>());
您可以将对象包装到包装器类中,然后可以实现hashcode
并仅基于对象的标识进行equals
。
You can extend HashSet
(or actually - AbstractSet
) , and back it with IdentityHashMap
which uses System.identityHashCode(object)
instead of obj.hashCode()
. 你可以扩展
HashSet
(或实际- AbstractSet
),并带回它IdentityHashMap
它采用System.identityHashCode(object)
,而不是obj.hashCode()
You can simply google for IdentityHashSet
, there are some implementations already. 您可以简单地用谷歌搜索
IdentityHashSet
,已经有一些实现。 Or use Collections.newSetFromMap(..)
as suggested by Joachim Sauer. 或按照Joachim Sauer的建议使用
Collections.newSetFromMap(..)
。
This of course should be done only if you are not in "possession" of your objects' classes. 当然,仅当您不属于对象类的“拥有”时,才应该这样做。 Otherwise just fix their
hashCode()
否则,只需修复其
hashCode()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.