Java – IdentityHashMap class with example

In this article, we will discuss IdentityHashMap class – one of the Map implemented classes in detail

1. Key points about IdentityHashMap:

  • IdentityHashMap is exactly same as that of HashMap with few differences

2. HashMap:

  • JVM uses equals() method to check uniqueness of keys before storing

3. IdentityHashMap:

  • JVM uses == operator to check uniqueness of keys before storing
30-IdentityHashMap-in-java

Source: Team BenchResources.Net

4. IdentityHashMap examples:

IdentityHashMapExample.java

package in.bench.resources.java.collection;

import java.util.IdentityHashMap;
import java.util.Set;

public class IdentityHashMapExample {

	public static void main(String[] args) {

		// creating IdentityHashMap object of type <Integer, String>
		IdentityHashMap<Integer, String> ihm =
				new IdentityHashMap<Integer, String>();

		// adding key-value pairs to IdentityHashMap object
		ihm.put(new Integer(1), "Google");
		ihm.put(new Integer(1), "Facebook");
		ihm.put(new Integer(1), "Yahoo");
		ihm.put(new Integer(1), "Amazon");
		ihm.put(new Integer(1), "Reddit");

		System.out.println("Printing all key-value pairs inside {}\n"
				+ ihm + "\n");

		System.out.println("\nIterating using keySet\n");

		// Iterating key-pairs using keySet
		Set<Integer> keys = ihm.keySet();
		for(Integer key : keys) {
			System.out.println(key + "  " + ihm.get(key));
		}

		System.out.println("\nSize of IdentityHashMap : "
				+ ihm.size());

		// removing map entry at 4th position
		System.out.println("\n\nEntry removed at 4th position : "
				+ ihm.remove(4));
	}
}

Output:

Printing all key-value pairs inside {}
{1=Amazon, 1=Yahoo, 1=Facebook, 1=Reddit, 1=Google}

Iterating using keySet

1  Amazon
1  Yahoo
1  Facebook
1  Reddit
1  Google

Size of IdentityHashMap : 5

Entry removed at 4th position : null

Explanation:

  • In HashMap, if we added same key even 5 times then it will contain only 1 key overriding previous value
  • Because, it uses equals() method to check for equality/comparison of keys
  • But in IdentityHashMap, it uses == operator to check for equality/comparison of keys (double equal to operator)
  • That is, it compares reference address or memory addresses
  • Since, memory address or references are different for different objects; therefore == operator returns false every time for new object added to IdentityHashMap even with same value
  • In this way, it contains 5 entries to IdentityHashMap

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java - WeakHashMap class with example
Java - HashMap vs LinkedHashMap