Java IdentityHashMap

In this tutorial, we will learn about java.util.IdentityHashMap, its features, use cases of it along with the working examples including explanation.


In Java, IdentityHashMap is an implementation of the Map interface that compares keys based on their reference equality instead of their object equality. It means if both object values are equals but their reference are different will be treated as unique objects. It means that it uses the == operator to determine whether two keys are the same, rather than the equals() method.

IdentityHashMap features:

  1. Unlike other implementations of the Map interface, IdentityHashMap does not use the equals() method to compare keys. Instead of equals method it uses the == operator to determine references of both the objects are equal?
  2. The IdentityHashMap implementation allows both keys and values to be null but for only one key.
  3. The order of iteration is not defined by the IdentityHashMap implementation. It may change from one invocation to the next depending on the hash codes of the keys.
  4. Because IdentityHashMap uses reference equality for key comparisons, there might be sligh performance improvement as it not requires to call equals method.

The use case of this class is very rare, where reference equality is needed instead of values equality this class can be used but again its very rare use case.

IdentityHashMap syntax and example:

Syntax :

IdentityHashMap<String,Integer> map = new IdentityHashMap<>();

Example 1:

In this example, we will add key-value pair with the different references but values of the keys are same.

import java.util.IdentityHashMap;
public class IdentityHashMapExample {
	public static void main(String[] args) {
		//Creating object of IdentityHashMap
		IdentityHashMap<String, Integer> map =  new IdentityHashMap<>();
		//creating a string object by passing value as Apple
		String fruit1 = new String("Apple");
		map.put(fruit1, 500);
		//passing Apple key as duplicate but it will not treat duplicates
		map.put("Apple", 12);
		map.put("Banana", 10);
		map.put("Orange", 5);
		map.put("Mango", 50);
		//remove key-value pair with new reference of Apple string but will not remove
		map.remove(new String("Apple"));

Output :

{Banana=10, Orange=5, Mango=50, Apple=12, Apple=500}
{Banana=10, Orange=5, Mango=50, Apple=12, Apple=500}

Explanation :

In the above example, we have created IdentityHashMap and added few elements which contains duplicates also but their references are different. Due to references different those were added into the map.

While removing the keys from the map it checks for the reference equality again due to this when we remove Apple key with new reference but it is not removed.

Conclusion :

In this tutorial, we have covered about the IdentityHashMap and how it working with syntax along with the working example of it.