WeakHashMap in Java

Posted on Updated on

A WeakHashMap is a special Map implementation where the keys of the map are stored in WeakReference. By storing the keys in a weak reference, key-value pairs can dynamically be dropped from the map when the only reference to the key is from the weak reference. This makes the WeakHashMap an excellent implementation for a weakly referenced list, where entries that aren’t used elsewhere may be dropped with no side effects.

Weakhashmap allow its entries to be garbage collected rather than waiting for full hashmap to be unused. So, it will automatically remove individual values when its key is no longer in ordinary use.

We can use a WeakHashmap to reduce the chance of a memory leak as a result of caching some object. Some features of WeakHashMap…

  1. WeakHashMap isn’t serialized.
  2. WeakHashMap permits null as key and value.
  3. Insertion order is not maintain in WeakHashMap.

WeakHashMap provides following constructors.

Constructor Description
WeakHashMap() Constructs a new, empty WeakHashMap with the default initial capacity (16) and load factor (0.75).
WeakHashMap(Map map) Constructs a new WeakHashMap with the same mappings as the specified map.
WeakHashMap(int initialCapacity) Constructs a new, empty WeakHashMap with the given initial capacity and the default load factor (0.75). Throws IllegalArgumentException if the initial capacity is negative.
WeakHashMap(int initialCapacity, float loadFactor) Constructs a new, empty WeakHashMap with the given initial capacity and the given load factor. Throws IllegalArgumentException if the initial capacity is negative, or if the load factor is nonpositive.

Example of WeakHashMap

Output

One thought on “WeakHashMap in Java

    Ashok Kumar said:
    March 16, 2016 at 7:21 am

    Great Job..Nice article…

Leave a Reply

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

Time limit is exhausted. Please reload CAPTCHA.