IdentityHashMap compares keys by == instead of equals().
Consider the below code.
It compares IdentityHashMap with HashMap.
import java.util.HashMap;
import java.util.IdentityHashMap;
public class IdentityHashMapTest
{
static IdentityHashMap<Integer, String> imap = new IdentityHashMap<Integer, String>();
static HashMap<Integer, String> hmap = new HashMap<Integer, String>();
public static void main(String[] args)
{
/* Put in an identity hash-map */
imap.put(new Integer(1), "ABC");
imap.put(new Integer(1), "DEF");
System.out.println(imap);
/* Put in a normal hash-map */
hmap.put(new Integer(1), "ABC");
hmap.put(new Integer(1), "DEF");
System.out.println(hmap);
}
}
Result:
{1=ABC, 1=DEF}
{1=DEF}
Explanation:
equals() method in Integer wrapper class compares values with the underlying integer value.
Due to this, a normal HashMap overwrites the value on second put() call.
However, an IdentityHashMap does not use the equals() method to determine equality.
It uses reference comparison (i.e. using ==), due to which it treats them as two separate keys.
Implementation Details
IdentityHashMap overrides the
hash(key) method such that it calls System.identityHashCode(key) instead of calling the regular key.hashCode()
This overridden method is
used for all the map functions
like contains(key), put(key, value) etc.
Got a thought to share or found a bug in the code? We'd love to hear from you: