javaweakhashmap

WeakHashMap example


I create a WeakHashMap as

WeakHashMap<Employee,String> map = new WeakHashMap<Employee,String>();
map.put(emp,"hello");

where emp is an Employee object. Now if I do emp = null or say emp object is no longer referenced, then will the entry be removed from the WeakHashMap i.e. will the size of Map be zero?
And will it be vice-versa in case of HashMap?
Is my understanding of WeakHashMap correct?


Solution

  • I ran the sample code to understand the difference between HashMap and WeakHashMap

                Map hashMap= new HashMap();
                Map weakHashMap = new WeakHashMap();
    
                String keyHashMap = new String("keyHashMap");
                String keyWeakHashMap = new String("keyWeakHashMap");
    
                hashMap.put(keyHashMap, "helloHash");
                weakHashMap.put(keyWeakHashMap, "helloWeakHash");
                System.out.println("Before: hash map value:"+hashMap.get("keyHashMap")+" and weak hash map value:"+weakHashMap.get("keyWeakHashMap"));
    
                keyHashMap = null;
                keyWeakHashMap = null;
    
                System.gc();  
    
                System.out.println("After: hash map value:"+hashMap.get("keyHashMap")+" and weak hash map value:"+weakHashMap.get("keyWeakHashMap"));
    

    The output will be:

    Before: hash map value:helloHash and weak hash map value:helloWeakHash
    After: hash map value:helloHash and weak hash map value:null