Reputation: 78421
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.
Upvotes: 17
Views: 6846
Reputation: 206786
I guess that java.util.IdentityHashMap
is what you're looking for (note, there's no IdentityHashSet
). Lookup the API documentation:
This class implements the
Map
interface with a hash table, using reference-equality in place of object-equality when comparing keys (and values). In other words, in anIdentityHashMap
, two keysk1
andk2
are considered equal if and only if(k1==k2)
. (In normalMap
implementations (likeHashMap
) two keysk1
andk2
are considered equal if and only if(k1==null ? k2==null : k1.equals(k2))
.)This class is not a general-purpose
Map
implementation! While this class implements theMap
interface, it intentionally violatesMap
's general contract, which mandates the use of theequals
method when comparing objects. 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
. You'd need to do something like this:
Set<E> mySet = Collections.newSetFromMap(new IdentityHashMap<E, Boolean>());
Upvotes: 29
Reputation: 597046
You can extend HashSet
(or actually - AbstractSet
) , and back it with IdentityHashMap
which uses System.identityHashCode(object)
instead of obj.hashCode()
.
You can simply google for IdentityHashSet
, there are some implementations already. Or use Collections.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()
Upvotes: 1
Reputation: 67750
You could wrap your objects into a wrapper class which could then implement hashcode
and equals
based simply on the object's identity.
Upvotes: 3