IdentityHashMap class in Java

Last Updated : 10 Apr, 2026

IdentityHashMap is a specialized Map implementation in the java.util package that compares keys based on memory reference rather than logical equality. It is useful when object identity matters more than content.

  • Compares keys using == instead of equals()
  • Uses System.identityHashCode() for hashing
  • Allows multiple keys with same content but different references

Declaration of IdentityHashMap

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

Java
import java.util.IdentityHashMap;

public class Example {
    public static void main(String[] args) {
        IdentityHashMap<String, Integer> identityHashMap = new IdentityHashMap<>();
        identityHashMap.put("A", 1);
        identityHashMap.put(new String("A"), 2);
        System.out.println(identityHashMap.size()); // 2
        System.out.println(identityHashMap.get("A")); // 1
    }
}

Output
2
1

Explanation: The IdentityHashMap class in Java is a hash table-based implementation of the Map interface that uses reference-equality in place of object-equality when comparing keys (and values).

The Hierarchy of IdentityHashMap

It implements Serializable, Cloneable, Map<K,? V> interfaces and extends AbstractMap<K, V> class.

map
IdentityHashMap

Internal Working of IdentityHashMap

IdentityHashMap in Java (programming language) stores key–value pairs using a hash table. It determines the storage position using System.identityHashCode() and compares keys using reference equality (==) instead of equals(). This means only the same object reference is treated as the same key.

  • Uses System.identityHashCode() for hashing keys.
  • Keys are compared using == (reference comparison).
  • Internally stores entries in an array in key–value pairs (key, value, key, value).

Constructors of IdentityHashMap

1. IdentityHashMap() 

Constructs a new, empty identity hash map with a default expected maximum size. 

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

2. IdentityHashMap(int expectedMaxSize)

Constructs a new, empty map with the specified expected maximum size. 

IdentityHashMap<K, V> ihm = new IdentityHashMap(int expectedMaxSize);

3. IdentityHashMap(Map m)

 Constructs a new identity hash map containing the key-value mappings in the specified map.

IdentityHashMap<K, V> ihm = new IdentityHashMap(Map m);

Java
import java.util.Map;
import java.util.HashMap;
import java.util.IdentityHashMap;

public class IdentityHashMapExample 
{
    public static void main(String[] args) 
    {
        // creating an instance of IdentityHashMap
        Map<String, String> ihm = new IdentityHashMap<>();

        // Putting key and value pair
        // in a IdentityHashMap Object
        ihm.put("ihmkey","ihmvalue"); 
        ihm.put(new String("ihmkey"),"ihmvalue1"); 
        
        // ihm.size() will print 2 since it 
        // compares the objects by reference
        System.out.println("Size of IdentityHashMap--"+ihm.size());
        
    }
}

Output
Size of IdentityHashMap--2

Basic Operations on IdentityHashMap

1. Adding Elements

To insert mappings into an IdentityHashMap, we use:

  • put(): inserts a key-value pair into the map.
  • putAll():copies all mappings from one map into another.
Java
import java.util.*;

public class AddingElementsToIdentityHashMap {
  
    public static void main(String[] args)
    {
        // Creating an empty IdentityHashMap
        Map<Integer, String> identity_hash
            = new IdentityHashMap<Integer, String>();

        // Mapping string values to int keys
        // using put() method
        identity_hash.put(10, "Geeks");
        identity_hash.put(15, "4");
        identity_hash.put(20, "Geeks");
        identity_hash.put(25, "Welcomes");
        identity_hash.put(30, "You");

        // Displaying the IdentityHashMap
        System.out.println("Initial Mappings are: "
                           + identity_hash);

        // Inserting existing key along with new value
          // previous value gets returned and stored in
          // returned_value
        String returned_value
            = (String)identity_hash.put(20, "All");

        // Verifying the returned value
        System.out.println("Returned value is: "
                           + returned_value);

        // Displaying the new map
        System.out.println("New map is: " + identity_hash);

        // Creating a new Identityhash map and copying
        Map<Integer, String> new_Identityhash_map
            = new IdentityHashMap<Integer, String>();
        new_Identityhash_map.putAll(identity_hash);

        // Displaying the final IdentityHashMap
        System.out.println("The new map: "
                           + new_Identityhash_map);
    }
}

Output
Initial Mappings are: {30=You, 10=Geeks, 15=4, 25=Welcomes, 20=Geeks}
Returned value is: Geeks
New map is: {30=You, 10=Geeks, 15=4, 25=Welcomes, 20=All}
The new map: {30=You, 10=Geeks, 15=4, 25=Welcomes, 20=All}

2. Removing Elements

We can remove the elements of an IdentityHashMap by using remove(). it removes the mapping associated with the specified key reference.

Java
import java.util.*; 

public class RemovingMappingsFromIdentityHashMap { 
    public static void main(String[] args) 
    { 

        // Creating an empty IdentityHashMap 
        Map<Integer, String> Identity_hash = new
                    IdentityHashMap<Integer, String>(); 
    
        // Mapping string values to int keys 
        Identity_hash.put(10, "Geeks"); 
        Identity_hash.put(15, "4"); 
        Identity_hash.put(20, "Geeks"); 
        Identity_hash.put(25, "Welcomes"); 
        Identity_hash.put(30, "You"); 

        // Displaying the IdentityHashMap 
        System.out.println("Initial Mappings are: " + 
                                        Identity_hash); 

        // Removing the existing key mapping 
        String returned_value = 
                        (String)Identity_hash.remove(20); 

        // Verifying the returned value 
        System.out.println("Returned value is: " + 
                                    returned_value); 

        // Displaying the new map 
        System.out.println("New map is: " + Identity_hash); 
    } 
} 

Output
Initial Mappings are: {30=You, 10=Geeks, 15=4, 25=Welcomes, 20=Geeks}
Returned value is: Geeks
New map is: {30=You, 10=Geeks, 15=4, 25=Welcomes}

3. Accessing the Elements

We can access the elements of an IdentityHashMap using the get() method, the example of this is given below.

Java
import java.util.*;

public class AccessingElementsFromIdentityHashMap {

    public static void main(String[] args)
    {

        // Creating an empty IdentityHashMap
        Map<Integer, String> identity_hash
            = new IdentityHashMap<Integer, String>();

        // Mapping string values to int keys
        identity_hash.put(10, "Geeks");
        identity_hash.put(15, "4");
        identity_hash.put(20, "Geeks");
        identity_hash.put(25, "Welcomes");
        identity_hash.put(30, "You");

        // Displaying the IdentityHashMap
        System.out.println("Initial Mappings are: "
                           + identity_hash);

        // Getting the value of 25
        System.out.println("The Value is: "
                           + identity_hash.get(25));

        // Getting the value of 10
        System.out.println("The Value is: "
                           + identity_hash.get(10));
      
          // Using keySet() to get the set view of keys 
        System.out.println("The set is: " + identity_hash.keySet()); 
          
          // Using entrySet() to get the set view 
        System.out.println("The set is: " + 
                                identity_hash.entrySet()); 
    }
}

Output
Initial Mappings are: {30=You, 10=Geeks, 15=4, 25=Welcomes, 20=Geeks}
The Value is: Welcomes
The Value is: Geeks
The set is: [30, 10, 15, 25, 20]
The set is: [30=You, 10=Geeks, 15=4, 25=Welcomes, 20=Geeks]

4. Traversing

We can traverse an IdentityHashMap using an Iterator with Map.Entry<?, ?>, and access each key–value pair using the next() method.

Java
import java.util.*;

public class IteratingIdentityHashMap {

    public static void main(String[] args)
    {

        // Creating an empty IdentityHashMap
        IdentityHashMap<Integer, String> identity_hash
            = new IdentityHashMap<Integer, String>();

        // Mapping string values to int keys
        identity_hash.put(10, "Geeks");
        identity_hash.put(15, "4");
        identity_hash.put(20, "Geeks");
        identity_hash.put(25, "Welcomes");
        identity_hash.put(30, "You");

        // Displaying the IdentityHashMap
        System.out.println("Initial Mappings are: "
                           + identity_hash);

        // Create an Iterator over the
        // IdentityHashMap
        Iterator<IdentityHashMap.Entry<Integer, String> >
            itr = identity_hash.entrySet().iterator();

        // The hasNext() method is used to check if there is
        // a next element The next() method is used to
        // retrieve the next element
        while (itr.hasNext()) {
            IdentityHashMap.Entry<Integer, String> entry
                = itr.next();
            System.out.println("Key = " + entry.getKey()
                               + ", Value = "
                               + entry.getValue());
        }
    }
}

Output
Initial Mappings are: {30=You, 10=Geeks, 15=4, 25=Welcomes, 20=Geeks}
Key = 30, Value = You
Key = 10, Value = Geeks
Key = 15, Value = 4
Key = 25, Value = Welcomes
Key = 20, Value = Geeks

Methods of IdentityHashMap

  • K – The type of the keys in the map.
  • V – The type of values mapped in the map.

METHOD

DESCRIPTION

clear()Removes all of the mappings from this map.
clone()Returns a shallow copy of this identity hash map: the keys and values themselves are not cloned.
containsKey(Object key)Tests whether the specified object reference is a key in this identity hash map.
containsValue(Object value)Tests whether the specified object reference is a value in this identity hash map.
entrySet()Returns a Set view of the mappings contained in this map.
equals(Object o)Compares the specified object with this map for equality.
get(Object key)Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
hashCode()Returns the hash code value for this map.
isEmpty()Returns true if this identity hash map contains no key-value mappings.
keySet()Returns an identity-based set view of the keys contained in this map.
put(K key, V value)Associates the specified value with the specified key in this identity hash map.
putAll(Map< extends K, extends V> m)Copies all of the mappings from the specified map to this map.
remove(Object key)Removes the mapping for this key from this map if present.
size()Returns the number of key-value mappings in this identity hash map.
values()Returns a Collection view of the values contained in this map.

IdentityHashMap Vs HashMap

Feature

IdentityHashMap

HashMap

Key Comparison

Uses reference equality (==)

Uses equals() method

Hashing Method

Uses System.identityHashCode()

Uses hashCode() method

Equality Logic

Keys are equal only if they refer to the same object in memory

Keys are equal if their content is equal

Thread Safety

Not synchronized

Not synchronized

Null Keys

Allows one null key

Allows one null key


Comment