Collection using reference equality

1k Views Asked by At

In Java is it possible to create HashMap that uses reference equality (i.e. ==) instead of the equals() method?

3

There are 3 best solutions below

0
On BEST ANSWER

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).

0
On

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;
}
0
On

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 Maps do so assuming that they will use equals, rather than reference equality. So be careful which functions you pass your IdentityHashmap to.