Java WeakHashMap class Example

By |2017-05-22T05:57:04+05:30June 16th, 2015|java|

In this tutorials, we are going to discuss a most important WeakHashMap class in collection framework and it is also very important for interview.

Java WeakHashMap :

The Java WeekHAshMap is one of the implementation class of the Map interface. It stores week  references are keys. If you don’t know what are week references you can see our detailed article on types of references here.

A WeakHashMap instance stores weak references to its keys, so that the garbage collector can reclaim memory used by keys that are not in use.

Some of the important characteristics of the WeakHashMap :

  • Automatic removal of a key after the garbage collector clears all the weak references to the key.

  • Each key object in a WeakHashMap is stored as the referent of a weak reference.

  • Automatic removal of entries in WeakHashMap when the associated keys are no longer used.

  • Support for null values and null keys.

Note: The performance of WeakHashMap is similar to HashMap class. The implementation of WeakHashMap class is not synchronized.

Constructors in the WeakHashMap class are:

  • WeakHashMap(): Creates an empty instance with the default initial capacity, 16, and fill ratio, 0.75.

  • WeakHashMap(int initialCapacity): Creates an empty instance with the specified initial capacity and default fill ratio.

  • WeakHashMap(int initialCapacity, float fillRatio): Creates an empty instance with the specified initial capacity and fill ratio.

  • WeakHashMap(Map<? extends K,? extends V>m): Creates an instance with the keys and values specified in the map m.

Methods in the WeakHashMap Class

Some of the most commonly used methods in the WeakHashMap class are:

  • V get(Object key): Returns the value mapped by the specified key.

  • V put(K key, V value):Inserts the specified value into the WeakHashMap and associates it with the specified key.

  • V remove(Object key): Removes the mapping associated with the specified key.

  • Set<Map.Entry<K,V>> entrySet():Returns a Set view of the WeakHashMap.

 Basic Operations on WeakHashMap

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;

public class WeakHashMapOperations {

    public static void main(String[] args) {
        // Creating the WeakHashMap with default constructor (Initial Capacity 16 and Load Factor 0.75)
        WeakHashMap weakHashMap = new WeakHashMap();
        // Adding Non-HomogeniousElements to WeakHashMap
        weakHashMap.put("a", 10);
        weakHashMap.put(10, 100);
        weakHashMap.put(100.0f, "Sample");
        weakHashMap.put(null, "Hello");
        weakHashMap.put(null, null);
        // Getting Elements from WeakHashMap using entrySet()
        Set entrySet = weakHashMap.entrySet();
        Iterator iterator = entrySet.iterator();
            Object next =;
            System.out.println("Key Values : "+next);
        // Getting Elements from WeakHashMap using keySet()
        Set keySet = weakHashMap.keySet();
        Iterator keyIterator = keySet.iterator();
            Object next =;
            System.out.println("Keys : "+next);
        // Check whether the key existed in WeakHashMap
        System.out.println("is 10 Existed as a Key : "+weakHashMap.containsKey(10));
        // Check whether the value existed in WeakHashMap
        System.out.println("is Sample Existed as a Key : "+weakHashMap.containsValue("Sample"));

[box type=”success” align=”alignleft” class=”” width=”100%”]
Key Values : 10=100
Key Values : 100.0=Sample
Key Values : a=10
Key Values : null=null
Keys : 10
Keys : 100.0
Keys : a
Keys : null
is 10 Existed as a Key : true
is Sample Existed as a Key : true

On the above example, we have done with the basic operations on WeakHashMap, But we didn’t take an advantage of WeakHashMap at all. Below is the example, which describes the actual importance of WeakHashMap compared to HashMap.

Java WeakHashMap class Example

When ever we use a WeakHashMap instance for storing the elements, the keys which are inserted in the WeakHashMap stored as weak references. If the key has been garbage collected, corresponding key entry will be deleted from the WeakHashMap. But this is not happened in  case of HashMap.  Find the below example for practical.

import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;

class WeakHashMapVsHashMap {

public static void main(String[] args) {
        Map hm = new HashMap();

        Map whm = new WeakHashMap();

        String keyHashMap = new String("10");
        String keyWeakHashMap = new String("20");

        hm.put(keyHashMap, "ten");
        whm.put(keyWeakHashMap, "twenty");
        System.out.println("Before Nullify the Keys : " + hm.get("10") + " :  " + whm.get("20"));

        keyHashMap = null;
        keyWeakHashMap = null;


        System.out.println("After Nullify the Keys : " + hm.get("10") + " :  " + whm.get("20"));

[box type=”success” align=”alignleft” class=”” width=”100%”]

Before Nullify the Keys : ten :  twenty
After Nullify the Keys : ten :  null


Happy Learning 🙂

About the Author:

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Leave A Comment