Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

Java – WeakHashMap

Declaration

class WeakHashMap<K, V>

WeakHashMap extends abstract class AbstractMap & implements Map interface.

It is similar to HashMap but if an object working with WeakHashMap does not have reference, it is eligible for garbage collection.

Whereas if an object working with HashMap does not have reference, it is not eligible for garbage collection.

List of WeakHashMap Constructors (CLICK HERE)

List of WeakHashMap Methods (CLICK HERE)

Non Generic Demo

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

Example

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

 public class WeakHashMapNonGenDemo 
 {
    public static void main(String args[]) 
    {
        WeakHashMap whm = new WeakHashMap();
        whm.put("James",55000);
        whm.put("Rohit",65000);
        whm.put("Poonam",75000);
        whm.put("Daisy", 85000);
        whm.put("Ricky", 95000);
	      
        System.out.println(whm);
	      
        System.out.println("\n After using Iterator :: ");
	      
        Set s = whm.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

{Poonam=75000, Ricky=95000, Daisy=85000, James=55000, Rohit=65000}

After using Iterator ::
Salary of Poonam is 75000
Salary of Ricky is 95000
Salary of Daisy is 85000
Salary of James is 55000
Salary of Rohit is 65000

Generic Demo

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

Example

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

 public class WeakHashMapGenericDemo 
 {
    public static void main(String args[]) 
    {
       WeakHashMap<String, Integer> lhm = new WeakHashMap<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

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

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

 

Leave a reply