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.
IdentityHashMap class
In Java, IdentityHashMap
is a class and 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.
Behaviour of IdentityHashMap:
- Unlike other implementations of the
Map
interface,IdentityHashMap
does not use theequals()
method to compare keys. Instead of equals method it uses the==
operator to determine references of both the objects are equal? - The
IdentityHashMap
implementation allows both keys and values to benull
but for only one key. - 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. - 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.
Syntax :
IdentityHashMap<String,Integer> map = new IdentityHashMap<>();
Example of IdentityHashMap with reference comparison:
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);
System.out.println(map);
//remove key-value pair with new reference of Apple string but will not remove
map.remove(new String("Apple"));
System.out.println(map);
}
}
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.