java中的对象引用集
我需要创建一组对象。担心的是我不想将散列或相等基于对象的 hashCode 和 equals 实现。相反,我希望哈希码和相等性仅基于每个对象的引用标识(即:引用指针的值)。
我不知道如何在 Java 中做到这一点。
这背后的原因是我的对象没有可靠地实现 equals 或 hashCode,在这种情况下引用标识就足够了。
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. Instead, I want the hash code and equality to be based only on each object's reference identity (i.e.: the value of the reference pointer).
I'm not sure how to do this in Java.
The reasoning behind this is my objects do not reliably implement equals or hashCode, and in this case reference identity is good enough.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我猜想
java.util.IdentityHashMap
是您要查找的内容(注意,没有
IdentityHashSet
)。查找API文档:编辑:请参阅下面 Joachim Sauer 的评论,基于特定
地图
制作集合
非常容易。你需要做这样的事情:I guess that
java.util.IdentityHashMap
is what you're looking for (note, there's noIdentityHashSet
). Lookup the API documentation:edit: See Joachim Sauer's comment below, it's really easy to make a
Set
based on a certainMap
. You'd need to do something like this:您可以将对象包装到包装类中,然后该包装类可以仅根据对象的标识实现
hashcode
和equals
。You could wrap your objects into a wrapper class which could then implement
hashcode
andequals
based simply on the object's identity.您可以扩展
HashSet
(或实际上 -AbstractSet
),并使用IdentityHashMap
使用System.identityHashCode(object)
而不是obj.hashCode()
。您可以简单地在 google 中搜索
IdentityHashSet
,已经有一些实现了。或者按照 Joachim Sauer 的建议使用Collections.newSetFromMap(..)
。当然,只有当您不“拥有”对象的类时才应该这样做。否则只需修复他们的
hashCode()
You can extend
HashSet
(or actually -AbstractSet
) , and back it withIdentityHashMap
which usesSystem.identityHashCode(object)
instead ofobj.hashCode()
.You can simply google for
IdentityHashSet
, there are some implementations already. Or useCollections.newSetFromMap(..)
as suggested by Joachim Sauer.This of course should be done only if you are not in "possession" of your objects' classes. Otherwise just fix their
hashCode()