In Java is it possible to create HashMap
that uses reference equality (i.e. ==
) instead of the equals()
method?
3 Answers
Use the IdentityHashMap
class. This is a variant of HashMap
in which ==
and System.identityHashCode()
are used instead of Object.equals(Object)
and Object.hashCode()
.
Note that this class intentionally violates the API contract of java.util.Map
which requires that key equality is based on equals(Object)
.

- 698,415
- 94
- 811
- 1,216
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.

- 1,415
- 3
- 14
- 29
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;
}

- 2,301
- 23
- 29