Java WeakHashMap - clear() Method
The java.util.WeakHashMap.clear() method is used to clear all key-value mappings of the map. This method makes the map empty with a size of zero.
Syntax
public void clear()
Parameters
No parameter is required.
Return Value
void type.
Exception
NA
Example:
In the example below, the java.util.WeakHashMap.clear() method is used to clear all key-value mappings of the given map.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a weakhashmap WeakHashMap<Integer, String> MyMap = new WeakHashMap<Integer, String>(); //populating the map MyMap.put(101, "John"); MyMap.put(102, "Marry"); MyMap.put(103, "Kim"); MyMap.put(104, "Jo"); //printing the map System.out.println("Before applying clear() method."); System.out.println("MyMap contains: " + MyMap); //clearing all mapping MyMap.clear(); //printing the map again System.out.println("\nAfter applying clear() method."); System.out.println("MyMap contains: " + MyMap); } }
The output of the above code will be:
Before applying clear() method. MyMap contains: {104=Jo, 101=John, 103=Kim, 102=Marry} After applying clear() method. MyMap contains: {}
❮ Java.util - WeakHashMap