×

IdentityHashMap in Java

The IdentityHashMap class is comparable to the HashMap class and is an AbstractMap implementation. However, when comparing the key, it uses reference equality rather than object equality (or values).

Identity HashMap is a non-general purpose Map implementation. While this class implements the Map interface, it deliberately violates Map's general contract by comparing objects using the equals () function.

It is designed particularly for the few occasions where reference-equality semantics are necessary. It is used when a user wishes to compare two things with the help of a reference.

To use the IdentityHashMap class, we must import the java.util package.

Features of IdentityHashMap:

  • It uses reference equality rather than the equals () approach. It makes use of the == operator.
  • Because it was not previously synchronized, IdentityHashMap must be synchronized externally.
  • Iterators throw a ConcurrentModificationException when attempting to modify during an iteration.
  • It ensures constant-time performance for simple operations like get and put, assuming the System. 
  • identityHashCode (Object) distributes the elements in the bucket properly. IdentityHashMap uses the System method rather than the hashCode () method. Method identityHashCode () () This is an important distinction since mutable objects can now be used as keys in Maps whose hash code is expected to change when the mapping is stored within IdentityHashMap.

Syntax:

public class IdentityHashMap <K,V>  extends AbstractMap <K,V> implements Map<K,V>, Serializable, Cloneable  

V- the value of an object

K- key

Constructors of IdentityHashMap:

IdentityHashMap instances can be created in two ways:

  • IdentityHashMap <K,V> object_ihm = new IdentityHashMap<K, V>( );
  • Map <K, V> object_hm = new IdentityHashMap<K, V> ( );

IdentityHashMap():  

It generates a new, empty identity hash map with the expected maximum size of 21.

Syntax:

IdentityHashMap <K, V> object = new IdentityHashMap<K, V>( );  

IdentityHashMap (int ExpectedMaxSize):

It generates a new, empty identity hash map with the specified maximum size.

Syntax:

IdentityHashMap <K, V> object= new IdentityHashMap(int ExpectedMaxSize);  

IdentityHashMap (Map m):

It generates a new identity hash map using the key-value pairs specified in the previous Map.

Syntax:

IdentityHashMap <K, V> object= new IdentityHashMap(Map m);  
MethodDescription
void clear ():It clears the Map, removing all mappings.
Set entrySet ():It returns a set view of the Map's key-value mapping.
Object put (Object Key, Object Value):It associates the supplied value with the given key in the identity hash map.
Object remove (Object Key):It removes from the Map all mappings for the provided key (if present).
Set keySet ():It returns an identity-based set view of the keys in the hash map.
void putAll (Map t) :The current Map receives all mappings from the given Map (in the argument). Any existing mappings for any keys supplied in the Map will be overwritten by these mappings.
Object clone ():It returns a shallow duplicate of the provided identity hash map. The keys and values, on the other hand, are not copied.
int size ():The identity hash map's key-value mapping count is returned.
boolean containsValue (Object Key):It checks to see if the supplied object reference is a value in the identity hash map.
boolean containsKey (Object Key):It checks to see if the supplied object is a key in the identity hash map.
boolean equals (Object o) :It compares the provided item to the Map to determine equality.
boolean isEmpty ():It returns true if the supplied identity hash map has no mappings.
Object get (Object key):It returns the value in the identity hash map that corresponds to the provided key. If there are no mappings for the key in the Map, it returns null.
Collection values():It returns the Map's value of a collection view.  
int hashCode():It returns the hash code value of the given Map.  

IdenHMapDemo.java:

// importing the pacakages and classes 
import java.util.Map;  
import java.util.HashMap;  
import java.util.IdentityHashMap;  
import java.util.*;  
public class IdenHMapDemo {  
   public static void main(String args[]) {  
      // instance- IdenHMapDemo   
      Map<String, String> idenHashmap = new IdentityHashMap<>();  
      // insert the elements -put method  
      //  key value pairs  
      idenHashmap.put("Priyanka", "101430");  
      idenHashmap.put("Shravani", "23240");  
      idenHashmap.put(new String("Shreya"), "23430");  
      idenHashmap.put("Anup", "45020");  
      idenHashmap.put("Nirnaya", "67705");  
      Set iSet = idenHashmap.entrySet();  
      Iterator i = iSet.iterator();  
      
      while(i.hasNext()) {  
         Map.Entry m= (Map.Entry)i.next();  
         System.out.print(m.getKey() + ": ");  
         System.out.println(m.getValue());  
      }  
      System.out.println();  
      // idenHashmap.size() comparing  objects through reference   
      // and printing the size of IdentityHashMap  
      System.out.println(" IdentityHashMap is: " + idenHashmap.size());  
   }  
}  

Output:

IdentityHashMap in Java

Operations on IdentityHashMap

Adding the elements:

To add entries to the IdentityHashMap, we utilize the put () and putAll () methods. The put () method adds the key and value supplied into the Map. When the current key is given, the previous value is replaced with the new value. PutAll () moves all key-value mappings from one Map to another.

IdenHMapDemoExample.java:

import java.util.*;  
public class IdenHMapDemoExample {  
    public static void main (String [] args)  
    {  
        
        Map<Integer, String> obj_ihm = new IdentityHashMap<Integer, String> ();  
        obj_ihm.put (1, "Hello");  
        obj_ihm.put (2, "??!");  
        obj_ihm.put (3, "welcome");  
        obj_ihm.put (4, "tutorials");  
        obj_ihm.put (5, "welcome");  
        // display IdentityHashMap  
        System.out.println (" mappings initially are: " + obj_ihm);  
        //  existing key with new value  
        //  past value stored in prev_value  
        String prev_value  = (String)obj_ihm.put (1, "Heyyy");  
        
        System.out.println ("\nReturned value is: "+ prev_value);  
        // displaying  new map  
        System.out.println ( "\nIdentityHashMap after assigning new value for the existing key:\n " + obj_ihm);  
        //  new Identityhashmap and  putAll ()  method
        Map<Integer, String> newHMap  = new IdentityHashMap<Integer, String> ();  
        newHMap.putAll (obj_ihm);  
        // Display final IdentityHashMap  
        System.out.println ("\n new IdentityHashMap : "+ newHMap);  
    }  
}  

Output:

IdentityHashMap in Java

Removing elements:

The remove () method is used to remove mappings (key-value pairs) from the Map.

IdenHMapDemoExample.java

import java.util.*;  
public class IdenHMapDemoExample {  
    public static void main ( String [] args)  
    {  
        Map<Integer, String> obj_ihm = new IdentityHashMap<Integer, String> ();  
        //  key - value pairs  
          
        obj_ihm.put (1, "Hello");  
        obj_ihm.put (2, "How");  
        obj_ihm.put (3, "Are");  
        obj_ihm.put (4, "You");  
        obj_ihm.put (5, "?");  
        //  IdentityHashMap  on output screen
        System.out.println ("mappings initially are: " + obj_ihm);  
        // removing  
        String return_value = (String)obj_ihm.remove (3);   
        // Displaying  new IdentityHashMap on the output screen   
        System.out.println ("\n IdentityHashMap is: " + obj_ihm);  
    }  
}  

Output:

IdentityHashMap in Java

Accessing the elements:

IdenHMapDemoExample.java:

import java.util.*;    
public class IdenHMapDemoExample {      
    public static void main (String [] args)  
    {  
        
        Map<Integer, String> obj_ihm = new IdentityHashMap<Integer, String>();    
        //  key - value pairs  
        
        obj_ihm.put (1, "Hello");  
        obj_ihm.put (2, "How");  
        obj_ihm.put (3, "Are");  
        obj_ihm.put (4, "You");  
        obj_ihm.put (5, "?");  
    
        //  IdentityHashMap  on the output screen
        System.out.println ("The  mappings initially are: " + obj_ihm);  
        // accessing  of 5  
        System.out.println ("Value of key 5 is:" + obj_ihm.get (5));  
        // accessing  of 2  
        System.out.println ("Value of key 2 is:"+ obj_ihm.get (2));  
        
        System.out.println ("Set view of keys: "+ obj_ihm.keySet ());  
        // set view using entrySet ()  
        System.out.println ("The set is: "+ obj_ihm.entrySet ());  
    }  
}  

Output:

IdentityHashMap in Java

Synchronized IdentityHashMap:

When several threads access the identity hash map at the same time, and at least one of them fundamentally updates the Map, the Map must be externally synchronized. (The addition or deletion of one or more key-value mappings is a structural map alteration. If we just modify the value associated with a key that an instance already has, this is not a structural modification.)

This may be accomplished by synchronizing on any object that includes the Map. If no such object exists, the Map should be wrapped in Collections. synchronizedMap method () This should be done at the time of creation to avoid unsynchronized access to the Map.

Syntax:

Map m = Collections.synchronizedMap (new IdentityHashMap(?));  

Related Topics

Java Solid Principles

Java implements the object-oriented SOLID principles for the design of software architecture. Solid Principles Java implements the object-oriented SOLID principles for the design of software architecture.   Five guiding principles transformed...

4 minutes read.

Graphics Program in Java

Graphics Program in Java The graphics program in Java is part of the Swing program in Java. In this section, we will learn about the implementation of custom graphics using some...

6 minutes read.

Iterate JSON array in Java

This article is going to equip the knowledge about what JSON array is and how it works and also how is it distinct with the generic array. Json Array Ordered lists of...

4 minutes read.

Moran Numbers in Java

In this article, we will be acknowledged about the moran numbers in Java, how they are formed, what are the approaches to achieve the moran numbers. Moran Number A moran numbers are...

3 minutes read.

Java While Keyword

Depending on a specified Boolean condition, a while loop in Java allows code to be executed repeatedly. The while loop can be viewed as an iterative version of the if...

3 minutes read.

Stack in Java

Java provides a number of collection frameworks to store the collection of objects. Among the collection of data structures " Stack " is one of them. Stack is one of...

5 minutes read.

Advanced Java Viva Questions

One of the more difficult languages available now is Java. Currently, 10 thousand developers worldwide use the programming language, which is rising daily. So, if you're a Java developer, an aspiring...

9 minutes read.

Java callable example

What is callable in Java? Callable is an interface that is present in Java. There are two methods for constructing threads: one is to inherit the Thread class, while the other...

3 minutes read.

Java Type Casting

Type casting is a technique or process used in Java to convert one data type into another, either manually or automatically. The compiler performs the automatic conversion, and the programmer...

3 minutes read.

Java Math atan2() Method

The atan2() method of Math class returns an angle theta from the conversion of rectangular coordinates to polar coordinates. Syntax: public static double atan2(double y, double x) Parameters: The parameter ‘y’ represents the ordinate...

3 minutes read.

Classes and Objects in Java Example Programs

Classes and Objects in Java Example Programs Java is an Object-Oriented programming language, i.e., everything in Java is associated with objects and objects are associated with classes. The classes and objects...

5 minutes read.

How to add Elements in Array in Java

Consider an array of the size n, in the given size we must add the elements in the given array. In this tutorial we are preferred to learn how to add...

3 minutes read.

How to add 4 Years to the Current Date in Java?

In this tutorial, we will learn how to add 4 years to the local or current date in Java language. We will begin our topic with basic concepts and would...

2 minutes read.

Java Try Resource

In Java, a try argument that specifies one or more resources is known as a try-with-resources statement. When your program is finished utilizing an object, it must be closed, which...

4 minutes read.

Abstract classes in Java

Abstract classes in Java Java uses the 'abstract’ keyword to make a class abstract. Such classes are known as abstract classes, and the process is known as abstraction. In programming language, abstract...

4 minutes read.

Java String trim() method

Java String trim() method returns String after eliminating leading and trailing spaces. Note:- Java String trim() method doesn't trim or omit middle spaces. Syntax: public String trim() Returns: It returns string with omitted leading and...

2 minutes read.

Types of Logical Operators in Java

In this tutorial, we are going to study logical operators. A logical operator is an operator that accomplishes a logical operation that is to connect two or more operations. These...

5 minutes read.

Set Up the Environment in Java

The Java is regarded as the pure object-oriented programming language. The Java applications are first compiled into the byte-code and then run by using the JVM. The Java is the...

4 minutes read.

Can we override Private Method in Java

In this article we will learn the concept of override, private method in java and we will now whether we can override private method in java or not. Override in Java Any...

3 minutes read.

LCM Program in Java

LCM Program in Java The LCM program in Java outputs the LCM of the given numbers. In Arithmetic, the lowest common multiple, least common multiple or smallest common multiple of the...

6 minutes read.