IdentityHashMap Class
In this tutorial, we are going to discuss about IdentityHashMap class in java. The IdentityHashMap
class in Java is a special implementation of the Map
interface that uses reference equality (identity comparison) instead of object equality (the equals()
method) to determine key equality.
In other words, it compares keys using the ==
operator rather than the equals()
method. This makes it different from other Map
implementations such as HashMap
or TreeMap
, which use the equals()
method for key comparison.
- It is exactly same as HashMap except the following differences
- In the case of HashMap JVM will always use “.equals()” method to identify duplicate keys, which is meant for content comparison.
- But in the case of IdentityHashMap JVM will use == (double equal operator) to identify duplicate keys, which is meant for reference comparison.
package com.ashok.collections;
import java.util.Map;
import java.util.HashMap;
import java.util.IdentityHashMap;
/**
*
* @author ashok.mariyala
*
*/
public class MyIdentityHashMap {
public static void main(String[] args) {
Map hashmapObject = new HashMap();
Map identityObject = new IdentityHashMap();
hashmapObject.put(new String("key"), "Ashok");
hashmapObject.put(new String("key"), "Vinod");
identityObject.put(new String("identityKey"), "Ashok");
identityObject.put(new String("identityKey"), "Vinod");
System.out.println("HashMap after adding key :" + hashmapObject);
System.out.println("IdentityHashMap after adding key :" + identityObject);
}
}
Output
HashMap after adding key :{key=Vinod}
IdentityHashMap after adding key :{identityKey=Ashok, identityKey=Vinod}
Key Features of IdentityHashMap:
- Reference Equality:
IdentityHashMap
uses reference equality to compare keys. Two keys are considered equal if they refer to the same object in memory. - No Concept of Hash Codes: Unlike other map implementations,
IdentityHashMap
does not rely on hash codes to determine key equality. It uses direct reference comparison instead. - Null Keys:
IdentityHashMap
allows one null key, similar to other map implementations. As null does not have a memory address, it can be uniquely identified. - Performance: Since
IdentityHashMap
relies on direct reference comparison, it can perform faster than other map implementations for certain use cases, especially when keys are compared using the equals() method. - Ordering:
IdentityHashMap
does not guarantee any specific iteration order of its elements, similar toHashMap
. - Not Synchronized: Like other map implementations,
IdentityHashMap
is not synchronized. If thread safety is required, synchronization must be handled externally.
That’s all about the IdentityHashMap class in java. If you have any queries or feedback, please write us email at contact@waytoeasylearn.com. Enjoy learning, Enjoy Java.!!
IdentityHashMap class