Collection using reference equality

In Java is it possible to create HashMap that uses reference equality instead of equals() method?


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

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

Need Your Help

How to store the selected data from a radiobuttonlist which is placed in a repeator in a database?


I am creating a survey form wherein I want the responses selected by the survey taker using the radiobuttonlist to be stored in the database. Since I have used a repeator to do this I am unable to ...

Warden vs Rack::Auth::Basic. Doing HTTP-Basic-Auth in Ruby-Framework

ruby-on-rails authentication rest

I want to create a WebService in Ruby (Sinatra, Padrino, maybe Ramaze... don't know yet...), but I definitely want to secure it...