5 Difference between HashMap and WeakHashMap in Java with Example

In this post ,we will learn about the difference between HashMap and WeakHashMap in java with example. We will also look into the similarities between HashMap and WeakHashMap . I have already shared difference between HashMap and Hashtable in java.

Read Also :  Difference between HashMap and HashSet in java with Example


Difference between HashMap and WeakHashMap in Java with Example 

1. Entry object Garbage Collected :  In HashMap , entry object(entry object stores key-value pairs) is not eligible for garbage collection .In other words, entry object will remain in the memory even if the key object associated with key-value pair is null.

According to WeakHashMap Oracle docs ,
An entry in a  WeakHashMap will automatically be removed when its key is no longer in ordinary use (even having mapping for a given key will not prevent the key from being discarded by the garbage collector that is made finalizable , finalized and then reclaimed). When a key is discarded then its entry is automatically removed from the map , in other words, garbage collected.



2. Key objects Reference :  In HashMap key objects have strong(also called soft) reference.

Each key object in the WeakHashMap  is stored indirectly as the referent of a Weak reference(also called hard ) reference.
Therefore , a key will automatically be removed only after the weak references to it , both inside and outside of the map , have been cleared by the garbage collector. Check here for  the difference between strong and weak reference.

3. Automatic Size decrease : Calling size()  method on HashMap object will return the same number of key-value pairs. size will decrease only if remove() method is called explicitly on the HashMap object.

Because the garbage collector may discard keys at anytime, a WeakHashMap may behave as though an unknown thread is silently removing entries. So it is possible for the size method to return smaller values over time.So, in WeakHashMap  size decrease happens automatically.

4.  Clone method :   HashMap implements Cloneable interface . HashMap class clone() method returns the shallow copy of the object , although , keys and values themselves are not cloned.

WeakHashMap does not implement Cloneable interface , it only implements Map interface. Hence , there is no clone() method in the WeakHashMap class.


5. Serialize and Deserialize objects : HashMap implements Serializable interface . So HashMap class object state can be serialized or deserialized (i.e state of the HashMap object can be saved and again resume from the saved state).

WeakHashMap does not implement Serializable interface . As a result , WeakHashMap object will not have any of their state serialized or deserialized.(i.e state of the WeakHashMap object cannot be saved and again resume from the saved state).

Example of WeakHashMap and HashMap 



import java.util.Map;
import java.util.HashMap;
import java.util.WeakHashMap;
public class WeakHashMapExample { public static void main(String[] args) { 
 
           
        // Created HashMap and WeakHashMap objects

        Map hashmapObject = new HashMap();
        Map weakhashmapObject = new WeakHashMap();
        
       // Created HashMap and WeakHashMap keys

        String hashmapKey = new String ("hashmapkey");
        String weakhashmapKey = new String ("weakhashmapkey");

      // Created HashMap and WeakHashMap values

        String hashmapValue = "hashmapvalue";
        String weakhashmapValue = "weakhashmapvalue";  

      // Putting key and value in HashMap and WeakHashMap Object

        hashmapObject.put(hashmapKey ,hashmapValue); 
        weakhashmapObject.put(weakhashmapKey ,weakhashmapValue); 


      // Print HashMap and WeakHashMap Object : Before Garbage Collection
       
        System.out.println("HashMap before Garbage Collected :"+ hashmapObject);
        System.out.println("WeakHashMap before Garbage Collected :"+
                            weakhashmapObject);

     // Set HashMap and WeakHashMap Object keys to null
        hashmapKey = null;  
        weakhashmapKey = null;

     // Calling Garbage Collection

        System.gc(); 

    // Print HashMap and WeakHashMap Object : After Garbage Collection
       
        System.out.println("HashMap after Garbage Collected :"+ hashmapObject);
        System.out.println("WeakHashMap after Garbage Collected :"+
                            weakhashmapObject); 
 }
}




Output :

HashMap before Garbage Collected :{hashmapkey=hashmapvalue}
WeakHashMap before Garbage Collected :{weakhashmapkey=weakhashmapvalue}
HashMap after Garbage Collected :{hashmapkey=hashmapvalue}
WeakHashMap after Garbage Collected :{}

   


When to Use WeakHashMap over HashMap 


difference between hashmap and weakhashmap with example

According to the  Effective Java Book,

WeakHashMap is useful only if the desired lifetime of cache entries  is determined by the external references to the key , not the value.
In short , WeakHashMap is useful for cache implementation .






Similarities between HashMap and WeakHashMap in Java

1. Null key and Null values :  Both classes (i.e WeakHashMap and HashMap ) permit null key and null values .

2. Performance : WeakHashMap class has the similar characteristics  as of the HashMap class and has the same efficiency parameters of initial capacity and load factor.

3. Not Synchronized : Both classes are not synchronized . Collections.synchronizedMap() can be used to synchronize both HashMap and WeakHashMap class.

4. Iterators returned by iterator method :  The iterators returned by the iterator method of  HashMap and WeakHashMap are fail-fast iterators. I have already discussed fail-safe vs fail-fast iterator with example.


Recap : Difference between HashMap and WeakHashMap in Java



HashMapWeakHashMap
Entry object Garbage CollectedNo ,even if key object is null Yes  
Key Object ReferenceStrongWeak
Automatic Size decreaseNo Yes
Clone methodYesNo
Serialize and Deserialize objects YesNo



Please mention in the comments in case you have any questions regarding the difference between HashMap and WeakHashMap in Java .

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry