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.
WeakHashMapis a kind ofMapimplemented based on theHashTable. TheWeakHashMaponly storesWeakReferencetypes 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
WeakHashMapclass. -
We create a
WeakHashMapobject, and use theput()method to add one mapping ({ten=10}) to themap. -
We use the
clear()method to remove all the mappings frommap. This makes themapempty. -
We print the
mapto ensure that it is empty.