In Java is it possible to create HashMap
that uses reference equality (i.e. ==
) instead of the equals()
method?
Collection using reference equality
1k Views Asked by zduny AtThere are 3 best solutions below

You can override the equals method of the objects you insert into the HashMap to test reference equality.
As in:
public boolean equals(Object obj) {
return this == obj;
}

The IdentityHashmap class comes with standard Java. From the JavaDoc:
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 an IdentityHashMap, two keys k1 and k2 are considered equal if and only if (k1==k2). (In normal Map implementations (like HashMap) two keys k1 and k2 are considered equal if and only if (k1==null ? k2==null : k1.equals(k2)).)
Be aware that many functions that take Map
s do so assuming that they will use equals
, rather than reference equality. So be careful which functions you pass your IdentityHashmap
to.
Use the
IdentityHashMap
class. This is a variant ofHashMap
in which==
andSystem.identityHashCode()
are used instead ofObject.equals(Object)
andObject.hashCode()
.Note that this class intentionally violates the API contract of
java.util.Map
which requires that key equality is based onequals(Object)
.