Difference between HashMap and WeakHashMap in Java

It is exactly same as HashMap except the below difference.

  • HashMap object is not eligible for Garbage collector even though it does not have any external references if it associated with HashMap.
  • Key of WeakHashMap has weak reference. I.e if the key is garbage collected, and then entry in WeakHashMap object will be deleted automatically. This is not the case in HashMap.

Example: See output. The entry in WeakHashMap object is deleted after t2=null.



Posted in collections and tagged , , .

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.