IdentityHashMap class in Java

Java 8Object Oriented ProgrammingProgramming

The IdentityHashMap class is similar to HashMap except that it uses reference equality when comparing the elements. This class is not a general-purpose Map implementation. While this class implements the Map interface, it intentionally violates Map's general contract, which mandates the use of the equals method when comparing objects.

Following are some of the methods of the IdentityHashMap class −

Sr.NoMethod & Description
1void clear()
Removes all mappings from this map.
2Object clone()
Returns a shallow copy of this identity hash map: the keys and values themselves are not cloned.
3boolean containsKey(Object key)
Tests whether the specified object reference is a key in this identity hash map.
4boolean containsValue(Object value)
Tests whether the specified object reference is a value in this identity hash map.
5Set entrySet()
Returns a set view of the mappings contained in this map.
6boolean equals(Object o)
Compares the specified object with this map for equality.
7Object get(Object key)
Returns the value to which the specified key is mapped in this identity hash map, or null if the map contains no mapping for this key.
8int hashCode()
Returns the hash code value for this map.

Following is an example to implement the IdentityHashMap class in Java −


 Live Demo

import java.util.*;
public class Main {
   public static void main(String args[]) {
      IdentityHashMap iHashMap = new IdentityHashMap();
      iHashMap.put("John", new Integer(10000));
      iHashMap.put("Tim", new Integer(25000));
      iHashMap.put("Adam", new Integer(15000));
      iHashMap.put("Katie", new Integer(30000));
      iHashMap.put("Jacob", new Integer(45000));
      iHashMap.put("Steve", new Integer(23000));
      iHashMap.put("Nathan", new Integer(25000));
      iHashMap.put("Amy", new Integer(27000));
      Set set = iHashMap.entrySet();
      Iterator iterator = set.iterator();
      while(iterator.hasNext()) {
         Map.Entry map = (Map.Entry);
         System.out.print(map.getKey() + ": ");
      System.out.println("Size of IdentintyHashMap: "+iHashMap.size());
      int bonus = ((Integer)iHashMap.get("Amy")).intValue();
      iHashMap.put("Amy", new Integer(bonus + 5000));
      System.out.println("Amy's salary after bonus = " + iHashMap.get("Amy"));
      int deductions = ((Integer)iHashMap.get("Steve")).intValue();
      iHashMap.put("Steve", new Integer(deductions - 3000));
      System.out.println("Steve's salary after deductions = " + iHashMap.get("Steve"));


Steve: 23000
Adam: 15000
Katie: 30000
Nathan: 25000
Tim: 25000
Amy: 27000
John: 10000
Jacob: 45000
Size of IdentintyHashMap: 8
Amy's salary after bonus = 32000
Steve's salary after deductions = 20000
Updated on 20-Sep-2019 07:32:47