Have a Question?

If you have any question you can ask below or enter what you are looking for!

What is IdentityHashMap?

What is IdentityHashMap?
What is IdentityHashMap?

What is IdentityHashMap?

What is IdentityHashMap?
  • In journal == operator meant for reference comparison (address comparison) and equals() method meant for content comparison.
  • It is exactly same as HashMap(including methods and constructors) except the following difference.
  • In the case of normal HashMap, JVM will use .equals() method to identify duplicates keys, which is meant for content comparison.
  • But in the case of identity HashMap JVM will use == operator to identify duplicate keys which are meant for reference comparison(address comparison).
  • This class implements the Map interface with a hash table, using reference-equality in place of object-equality when comparing keys (and values).
  • The map is a special implementation that only supports Identity-based Equality.
  • IdentityHashMap compares keys reference(i.e using ==) , where as HashMap compares Objects.
  • IdentityHashMap use System.identityHashCode(key) for generating a hashcode, where as HashMap uses hashcode(key) for generating a unique hashcode.
  • Initial capacity of IndentityHashMap is 21, whereas HashMap has 16.
  • IdentityHashMap violates Map contract by comparing reference, whereas HashMap doesn’t.
  • If you see the below output for both IdentityHashMap and HashMap, you can find that IdenityHashMap allows duplicate keys and values(because of reference comparison), whereas HashMap doesn’t allow(because of Object comparison)
package com.java4us;

import java.util.IdentityHashMap;

class Test {
    public static void main(String[] args) {
        Integer i1 = new Integer(10);
        Integer i2 = new Integer(10);
         * HashMap map = new HashMap();
         * map.put(i1, "Raja");
         * map.put(i2, "Rani");
         * System.out.println(map); // {{10=Rani}}
        IdentityHashMap map = new IdentityHashMap();
        map.put(i1, "Raja");
        map.put(i2, "Rani");
        System.out.println(map);    //{10=Rani, 10=Raja}
  • I1 and i2 are duplicates keys because i1.equals(i2) returns true.
  • If we replace HashMap with IdentityHashMap then i1 and i2 are not duplicate keys because i1==i2 returns false.

Leave a Reply

Your email address will not be published. Required fields are marked *