HashMap Vs WeakHashMap

Posted on Updated on

While working with Collection framework I came to know about WeakHashMap. The first question came to my mind, Java has already lots of concrete classes for Map interface then why another class WeakHashMap. There are some basic difference between HashMap and WeakHashMap. For more about WeakHashMap you can refer here. In interviews, it is very common to ask question for WeakHashMap Vs HashMap. Here are some differences between HashMap and WeakHashMap.

Difference between HashMap and WeakHashMap.

WeakHashMap HashMap
An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. More precisely the presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector. Entry will be in memory even if it is not in use.
In WeakHashMap, keys of the map are stored in a java.lang.ref.WeakReference thus have weak reference.", In HashMap keys of map have strong reference."
WeakHashMap doesn't implements Serializable interface.So, we can't Serialize or Deserialized object of WeakHashMap. HashMap implements Serializable interface. So, we can Serialized/Deserialized object of HashMap.
WeakHashMap doesn't implements Cloneable interface. So, there is no clone method in WeakHashMap. HashMap implements Cloneable interface and return shallow copy of the object while calling clone method.
WeakHashMap is useful for cache implementation where entries  is determined by the external references to the key, not the value. HashMap is useful to store key-value pair irrespective of external references.

There are some similarity between HashMap and WeakHashMap.

  1. Both classes are not serialized.
  2. Both classes permit null as key and value.
  3. Default initial capacity and load factor is same for both classes.(initialCapacity : 16, loadFactor : 0.75).
  4. Insertion order is not maintain in HashMap and WeakHashMap.

Example

Output

Leave a Reply

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

Time limit is exhausted. Please reload CAPTCHA.