IdentityHashMap in Java | Methods, Example

IdentityHashMap in Java is a concrete class that is similar to HashMap except that it uses reference equality (==) when comparing entries (keys and values).

In simple words, Java IdentityHashMap uses reference equality (==) instead of object equality (equals() method) when comparing keys and values.

While comparing keys, HashMap uses the equals() method whereas IdentityHashMap uses reference equality (==).

In HashMap, two keys k1 and k2 are considered equal if and only if (k1==null?k2==null:k1.equals(k2)).  In IdentityHashMap, two keys are considered equal if and only if (k1==k2).

IdentityHashMap in Java was added in JDK 1.4 version and is present in java.util.IdentityHashMap package. This class is rarely used in the program.

Hierarchy of IdentityHashMap in Java


Java IdentityHashMap class extends AbstractMap class and implements Map interface (by using a hash table). The hierarchy diagram of IdentityHashMap is shown in the below figure.Java IdentityHashMap hierarchy diagram

IdentityHashMap class declaration


IdentityHashMap is a generic class that can be declared as follows:

class IdentityHashMap<K,V>
  extends AbstractMap<K,V>
    implements Map<K,V>

Here, K defined the type of keys and V defines the type of Values. The API documentation explicitly states that IdentityHashMap is not for general use.

Features of IdentityHashMap


There are several important features of IdentityHashMap in Java that should keep in mind. They are as:

1. IdentityHashMap allows us to store data in the form of key-value pairs.

2. In IdentityHashMap, only one null key is allowed to add but many null values can be inserted.

3. Like HashMap, IdentityHashMap does not maintain insertion order. There is no guarantee that elements will be retrieved in the same order as we have inserted.


4. It is not synchronized. That means it is not thread-safe. So, two or more threads on same IdentityHashMap object can access it at the same time.

We can synchronize IdentityHashMap by using Collections’s class synchronizedMap() method. The syntax to synchronize it is as follows:

Map synchronizedMap = Collections.synchronizedMap(IdentityHashMap);

Now, no two or more threads can access the same object of map simultaneously.

5. Iterator returned by IdentityHashMap is a fail-fast. That means any structural modification made to IdentityHashMap like adding or removing elements during Iteration will throw an exception named ConcurrentModificationException.

Constructors of IdentityHashMap class


Java IdentityHashMap has the following three public constructors:

  • public IdentityHashMap()
  • public IdentityHashMap(int ems)
  • public IdentityHashMap(Map m)

The first two constructors are standard that are used for general-purpose Map implementation. They create an empty IdentityHashMap with expected maximum size of 21 (by default) and ems. The expected maximum size ems is the maximum number of entries that are expected to hold.

The third constructor creates IdentityHashMap containing the same entries that are present in Map m.

IdentityHashMap Methods in Java


IdentityHashMap methods are exactly the same as HashMap’s methods. So, let’s perform some operations based on the IdentityHashMap methods and see the difference between HashMap and IdentityHashMap.

Java IdentityHashMap Example Programs


Let’s create a program where we will see the difference between HashMap and IdentityHashMap. Look at the following source code to understand better.

Program source code 1:

import java.util.HashMap;
import java.util.IdentityHashMap;

public class IdentityHashMapEx1 {
public static void main(String[] args) 
{
// Create a HashMap.	
 HashMap<String, String> hmap = new HashMap<>();
 
 String s1 = new String("R");
 String s2 = new String("R");

// Adding entries in HashMap.
  hmap.put(s1, "Red");
  hmap.put(s2, "Red");

System.out.println("Keys present in HashMap hmap: " +hmap.keySet());
System.out.println("Values present in HashMap hmap: " +hmap.values());

// Create a IdentityHashMap object.
 IdentityHashMap<String, String> ihmap = new IdentityHashMap<>();
  ihmap.put(s1, "Red");
  ihmap.put(s2, "Red");
  
System.out.println("\n");  
System.out.println("Keys present in IdentityHashMap: " +ihmap.keySet());
System.out.println("Values present in IdentityHashMap: " +ihmap.values());
 }
}
Output:
     Keys present in HashMap hmap: [R]
     Values present in HashMap hmap: [Red]

     Keys present in IdentityHashMap: [R, R]
     Values present in IdentityHashMap: [Red, Red]

Explanation:

1. In the preceding program, an empty HashMap is created. Then two separate strings s1 and s2, each pointing to R, are created. They are used as keys having corresponding values R and put both keys s1 and s2 in the hash map along with their values.

2. Then keys are retrieved using keySet() method and displayed on the console. In the output, you will observe that only one key R is displayed on the console.

3. Values are retrieved using values() method and displayed on the console. The value Red is displayed on the screen.

This is because HashMap uses equals() method for comparing keys. Since both s1 and s2 contain the same contents (i.e. Red), therefore, equals() method will return true.

When an attempt is made to put s2 along with its associated value, it replaces the value. Thus, only one entry (key-value pair) is retained.

4. Now an empty IdentityHashMap ihmap is created. Both s1 and s2 are inserted in the identity hash map object along with their values.

5. Then keySet() method is used to retrieve keys. Both keys, each having values R, are displayed on the screen.

6. values() method is used to retrieve values. Both values, each containing value “Red”, are displayed on the screen. As you can see in the output.

This is because IdentityHashMap uses == operator for comparing keys. Since both s1 and s2 are two different objects (although they contain the same value “Red”), the == operator will return false.

An attempt is made to put s2 along with its value in the IdentityHashMap, the second key-value pair will be considered as different key-value pair and added to the identity hash map.

Although, Java IdentityHashMap implements Map interface, still, this class violates Map’s general contract of using equals() method during the comparison of key objects.

Therefore, it is not for general use. IdentityHashMap can be used only in cases where reference-equality semantic are required.

2. Let’s take an example program based on the following methods of IdentityHashMap. We will perform the following operations. Look at the source code.

Program source code 2:

import java.util.IdentityHashMap;
public class IdentityHashMapEx2 {
public static void main(String[] args) 
{
 String s1 = new String("R");
 String s2 = new String("G");

// Create a IdentityHashMap object.
IdentityHashMap<String, String> ihmap = new IdentityHashMap<>();
  
  ihmap.put(s1, "Red");
  ihmap.put(s2, "Green");
 
System.out.println("Keys present in IdentityHashMap: " +ihmap.keySet());
System.out.println("Values present in IdentityHashMap: " +ihmap.values());

// Inserting some more keys and values.
  ihmap.put("P", "Pink");
  ihmap.put("B", "Black");
  ihmap.put("W", "White");
  ihmap.put("O", "Orange");

System.out.println("\n");  
System.out.println("IdentityHashMap contains key P: " +ihmap.containsKey("P"));

System.out.println("IdentityHashMap contains value Orange: " +ihmap.containsValue("Orange"));
System.out.println("Set of mappings contained in ihmap: " +ihmap.entrySet());

System.out.println("Value corresponding to key W: " +ihmap.get("W"));
System.out.println("Is IdentityHashMap ihmap empty: " +ihmap.isEmpty());

ihmap.clear();
System.out.println("After using clear() method ihmap contains: " +ihmap);
  }
}
Output:
      Keys present in IdentityHashMap: [R, G]
      Values present in IdentityHashMap: [Red, Green]

      IdentityHashMap contains key P: true
      IdentityHashMap contains value Orange: true

      Set of mappings contained in ihmap: [R=Red, P=Pink, O=Orange, W=White, B=Black, G=Green]
      Value corresponding to key W: White
      Is IdentityHashMap ihmap empty: false
      After using clear() method ihmap contains: {}

When to use IdentityHashMap in Java?


IdentityHashMap can be used when:

  • We want to perform deep-copying.
  • We want to maintain proxy objects.
  • We want to store only one null key on the map.
  • We do not want the insertion order of entries.
  • We are not working in a multithreading environment.

Hope that this tutorial has covered important points about IdentityHashMap in Java with example programs. I hope that you will have understood this topic.
Thanks for reading!!!
Next ⇒ EnumMap in Java⇐ PrevNext ⇒