What is the WeakHashMap.clear() method in Java?

The clear() method of the WeakHashMap class in Java removes all key and value mappings from a specified WeakHashMap object. After this method is called, the WeakHashMap object becomes empty.

WeakHashMap is a kind of Map implemented based on the HashTable. The WeakHashMap only stores WeakReference types as their keys. Once the key is no longer used, the respective mapping is automatically removed during garbage collection.

Syntax

public void clear()

This method doesn’t take any parameters, and does not return a value.

Code

The code below shows how to use the clear() method.

import java.util.WeakHashMap;
class WeakHashMapClearExample {
public static void main( String args[] ) {
WeakHashMap<String, Integer> map = new WeakHashMap<>();
String key = new String("ten");
map.put(key, 10);
System.out.println("WeakHashMap is : "+ map);
map.clear();
System.out.println("\nAfter Calling Clear method");
System.out.println("\nWeakHashMap is : " + map);
}
}

Explanation

In the code above:

  • We import the WeakHashMap class.

  • We create a WeakHashMap object, and use the put() method to add one mapping ({ten=10}) to the map.

  • We use the clear() method to remove all the mappings from map. This makes the map empty.

  • We print the map to ensure that it is empty.