Java Identity HashMap Examples

Published May 20, 2022

Just as its name implies, the identityHashMap is a hashtable based on the implementation of the Map interface. You should use the IdentityHashMap class when the reference-equality semantics are needed. Instead of using the equals method, the IdentityHashmap compares each key using the ‘==’ method.

In spite of the fact that this class implements the map interface in Java, it intentionally contravenes the map's general contract, which necessitates the use of the equals method during the comparison of the objects.

Now let’s look at an example of a Java IdentityHashMap

 

An Example of Java IdentityHashmap

import java.util.IdentityHashMap;

public class Java_identityHashMap {

            public static void main(String[] args) {

                        final IdentityHashMap<String, String> myidentityHashMap = new IdentityHashMap<String, String>();

                        myidentityHashMap.put("First", "Java");

                        myidentityHashMap.put("second", "Python");

                        myidentityHashMap.put("Third", "Kotlin");

         for (final String str : myidentityHashMap.keySet()) {

             System.out.println("Key : " + str + " and Value : " + myidentityHashMap.get(str));

         }

         System.out.println("Our Map size is : " + myidentityHashMap.size());

        System.out.println("Here are opur Map Keys");

            }

}

 

Output

Key: Third and Value : Kotlin

Key : second and Value : Python

Key : First and Value : Java

Our Map size is : 3

Here are opur Map Keys

 

Keywords: Java Identity HashMaps , HashMap, Java Collections

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

56 Views