Skip to content
Related Articles

Related Articles

Improve Article

Java Program to Implement IdentityHashMap API

  • Last Updated : 13 Apr, 2021

The IdentityHashMap implements Map interface using Hashtable, using reference-equality in place of object-equality when comparing keys (and values). This class is not a general-purpose Map implementation. While this class implements the Map interface, it intentionally violates Map’s general contract, which mandates the use of the equals() method when comparing objects. This class is used when the user requires the objects to be compared via reference. It belongs to java.util package. It was later added in Java 1.4

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

The main difference between IdentityHashMap and HashMap in java is that IdentityHashMap is a special implementation of Map interface which doesn’t use equals(obj) and hashCode() method for comparing object unlike other implementation of Map e.g. HashMap. Instead, IdentityHashMap uses the equality operator “==” to compare keys and values in Java which makes it faster compared to HashMap and suitable where you need reference equality check instead of logical equality.

Differences between IdentityHashMap and HashMap are as follows:



  1. The main difference between HashMap vs IdentityHashMap is that IdentityHashMap uses the equality operator “==” for comparing keys and values inside Map while HashMap uses equals(obj) method for comparing keys and values.
  2. Since IdentityHashMap doesn’t use equals(obj), its comparatively faster than HashMap for object with expensive equals(obj) and hashCode().
  3. One more difference between HashMap and IdentityHashMap is the immutability of the key. One of the basic requirements of safety, when we store objects in HashMap, is keys need to be immutable, IdentityHashMap doesn’t require keys to be immutable as it does not rely on equals(obj) and hashCode().

Example 1:

Java




// Java Program to illustrate IdentityHashMap by
// Differenciating between HashMap and IdentityHashMap
 
// Importing input output classes
import java.io.*;
// Importing HashMap, IdentityHashMap and Map classes
// from java.util package
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Map;
 
// Main Class
public class GFG {
 
    // Main driver method
    public static void main (String[] args) {
 
        // Creating objects of HashMap and IdentityHashMap objects
        // Declaring objects of type String and Integer type
        Map<String, Integer> hashMap = new HashMap<String, Integer>();
        Map<String, Integer> identityHashMap = new IdentityHashMap<String, Integer>();
 
        // Adding elements to objects of Maps created above
        // Elements are of type key-value pairs using put() method
        // Custom entries
        hashMap.put("Scala", 100);
        hashMap.put(new String("Scala"), 101);
        hashMap.put("Groovy", 56);
        hashMap.put(new String("Groovy"), 57);
 
        identityHashMap.put("Ruby", 25);
        identityHashMap.put(new String("Ruby"), 27);
        identityHashMap.put("Swift", 12);
        identityHashMap.put(new String("Swift"), 13);
 
 
        // hashMap.size() will print 2 since
        // it compares the objects logically and both the keys are same
        System.out.println("Size of HashMap is : " + hashMap.size());
 
        // identityHashMap.size() will print 4 since
        // it compares the objects by reference
        System.out.println("Size of IdentityHashMap is : " + identityHashMap.size());
    }
}

 
 

Output
Size of HashMap is : 2
Size of IdentityHashMap is : 4

Implementation: HashMap uses hashCode() to find bucket location. IdentityHashMap doesn’t use hashCode(), instead it uses System.identityHashCode(object).

Example 2:

Java




// Java Program to illustrate IdentityHashMap by
// Differenciating between HashMap and IdentityHashMap
 
// Importing input output classes
import java.io.*;
// Importing Map,HashMap and IdentityHashMap classes
// from java.util package
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Map;
 
// Class 1
// Helper Class
class ProgrammingLanguage {
 
    // Member variables of this class
    private String language;
    private Integer value;
 
    // Constructor of this class
    public ProgrammingLanguage(String language,
                               Integer value)
    {
 
        // this keyword refers to current objectc itself
        this.language = language;
        this.value = value;
    }
 
    // Method 1
    public String getlanguage()
    {
 
        // Returning language
        return language;
    }
 
    // Method 2
    public Integer getValue()
    {
 
        // Returning value associated with a language
        return value;
    }
 
    // Method 3
    // Sets a new value for a languauge
    public void setValue(Integer value)
    {
        this.value = value;
    }
 
    // Method 4
    // @Override
    public int hashCode()
    {
        final int prime = 31;
        int result = 1;
        result
            = prime * result
              + ((language == null) ? 0 : value.hashCode());
        result
            = prime * result
              + ((language == null) ? null
                                    : language.hashCode());
        return result;
    }
 
    // Method 5
    // @Override
    public boolean equals(Object obj)
    {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        ProgrammingLanguage other
            = (ProgrammingLanguage)obj;
        if (value == null) {
            if (other.value != null)
                return false;
        }
        else if (!value.equals(other.value))
            return false;
        if (language == null) {
            if (other.language != null)
                return false;
        }
        else if (!language.equals(other.language))
            return false;
        return true;
    }
}
 
// Class 2
// Main Class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        ProgrammingLanguage groovy
            = new ProgrammingLanguage("Groovy", 1000);
        ProgrammingLanguage scala
            = new ProgrammingLanguage("Scala", 2000);
        ProgrammingLanguage ruby
            = new ProgrammingLanguage("Ruby", 3000);
 
        Map<ProgrammingLanguage, Integer> languageValue
            = new HashMap<>();
        Map<ProgrammingLanguage, Integer>
            languageValueIdentity = new IdentityHashMap<>();
 
        // Inserting elements to object of HashMap created
        // Custom entries
        languageValue.put(groovy, groovy.getValue());
        languageValue.put(scala, scala.getValue());
        languageValue.put(ruby, ruby.getValue());
 
        // Inserting elements to object of IdenityHashMap
        // created Custom entries
        languageValueIdentity.put(groovy,
                                  groovy.getValue());
        languageValueIdentity.put(scala, scala.getValue());
        languageValueIdentity.put(ruby, ruby.getValue());
 
        // Display message only
        System.out.println("Before modifying keys  :  ");
 
        String result = languageValue.get(groovy) != null
                            ? "Yes"
                            : "No";
 
        // Print commands to Display the result
        System.out.println(
            "Does Groovy language exists in HashMap? "
            + result);
 
        result = languageValueIdentity.get(groovy) != null
                     ? "Yes"
                     : "No";
 
        System.out.println(
            "Does Groovy language in IdenityHashMap? "
            + result);
 
        // Now, modifying the value object
        groovy.setValue(5000);
 
        // Display message only
        System.out.println("After modifying keys  :  ");
 
        // Print commands to Display the result
        result = languageValue.get(groovy) != null ? " Yes "
                                                   : " No ";
 
        System.out.println(
            "Does Groovy language exists in HashMap? "
            + result);
 
        result = languageValueIdentity.get(groovy) != null
                     ? " Yes "
                     : " No ";
 
        System.out.println(
            "Does Groovy language exists in IdenityHashMap? "
            + result);
    }
}
Output
Before modifying keys  :  
Does Groovy language exists in HashMap? Yes
Does Groovy language in IdenityHashMap? Yes
After modifying keys  :  
Does Groovy language exists in HashMap?  No 
Does Groovy language exists in IdenityHashMap?  Yes 

Output explanation: 

It is clear from the output that once the programming language object is changed, which is key in both HashMap and IdentityHashMap, we are unable to retrieve an object in the case of HashMap but are able to retrieve when you use IdentityHashMap because the former uses equals() method which returns false once the value is changed and latter uses “==” operator which returns true because in both cases the object is the same in heap.




My Personal Notes arrow_drop_up
Recommended Articles
Page :