Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

Java – IdentityHashMap

Declaration

class IdentityHashMap<K,V>

IdentityHashMap extends abstract class AbstractMap & implements the Map interface.

It is similar to the HashMap but there is one difference among them.

IdentityHashMap uses reference equality (==) to compare elements within the map whereas HashMap uses equals() method to compare elements within the map.

List of IdentityHashMap Constructors (CLICK HERE)

List of IdentityHashMap Methods (CLICK HERE)

Non Generic Demo

Non generic IdentityHashMap can contain any type of keys & values.

Example

 import java.util.IdentityHashMap;
 import java.util.Iterator;
 import java.util.Map;
 import java.util.Set;

 public class IdentityHashMapNonGenDemo 
 {
     public static void main(String args[]) 
     {
         IdentityHashMap ihm = new IdentityHashMap();
         ihm.put("James",5000);
         ihm.put("Rohit",6000);
         ihm.put("Poonam",7000);
         ihm.put("Daisy", 8000);
         ihm.put("Ricky", 9000);
	      
         System.out.println(ihm);
	      
         System.out.println("\n After using Iterator :: ");
	      
         Set s = ihm.entrySet();
         Iterator itr = s.iterator();
	      
         while(itr.hasNext())
         {
             Map.Entry m = (Map.Entry)itr.next();
             System.out.println("Salary of "+m.getKey() + " is "+m.getValue());
         }
     }
 }

Output

{James=5000, Poonam=7000, Ricky=9000, Daisy=8000, Rohit=6000}

After using Iterator ::
Salary of James is 5000
Salary of Poonam is 7000
Salary of Ricky is 9000
Salary of Daisy is 8000
Salary of Rohit is 6000

Generic Demo

Generic type IdentityHashMap allows storing keys & values only of type, specified during declaration.

Example

 import java.util.IdentityHashMap;
 import java.util.Iterator;
 import java.util.Map;
 import java.util.Map.Entry;
 import java.util.Set;

 public class IdentityHashMapGenericDemo 
 {
    public static void main(String args[]) 
    {
       IdentityHashMap<String, Integer> lhm = new IdentityHashMap<String, Integer>();
       lhm.put("James",5000);
       lhm.put("Rohit",6000);
       lhm.put("Poonam",7000);
       lhm.put("Daisy",8000);
       lhm.put("Ricky",9000);
	      
       System.out.println(lhm);
	      
       System.out.println("\n After using Iterator :: ");
	      
       Set<Map.Entry<String, Integer>> s = lhm.entrySet();
       Iterator<Entry<String, Integer>> itr = s.iterator();
	      
       while(itr.hasNext())
       {
           Map.Entry<String, Integer> m = (Entry<String, Integer>)itr.next();
           System.out.println("Salary of "+m.getKey() + " is "+m.getValue());
       }
    }
 }

Output

{James=5000, Poonam=7000, Ricky=9000, Daisy=8000, Rohit=6000}

After using Iterator ::
Salary of James is 5000
Salary of Poonam is 7000
Salary of Ricky is 9000
Salary of Daisy is 8000
Salary of Rohit is 6000

 

Leave a reply