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.
A reference is an address that indicates where an object's variables and methods are stored. You aren't actually using objects when you assign an object to a variable or pass an object to a method as an argument. You aren't even using copies of the objects. Instead, you're using references to those objects.
A variable whose type is a class contains a reference to an object of the class (i.e., the address of the memory location where the object is allocated). Example: String s; s = "xxx"; The first statement declares a variable s of type String. Such a variable is not initialized yet.
The concept of object references becomes clear when assigning the same object to more than one property. Rather than holding a copy of the object, each assigned property holds object references that link to the same object, so that when the object changes all properties referring to the object reflect the change.
When you create an object of a class as − Student obj = new Student(); The objects are created in the heap area and, the reference obj just points out to the object of the Student class in the heap, i.e. it just holds the memory address of the object (in the heap).
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>());
You could wrap your objects into a wrapper class which could then implement hashcode
and equals
based simply on the object's identity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With