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.

 Output:

 

Posted in collections and tagged , , .

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">