Java Utility Library

Java IdentityHashMap - clear() Method



The java.util.IdentityHashMap.clear() method is used to clear all key-value mappings of this 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.IdentityHashMap.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 identity hash map
    IdentityHashMap<Integer, String> MyMap = new IdentityHashMap<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: {102=Marry, 104=Jo, 103=Kim, 101=John}

After applying clear() method.
MyMap contains: {}

❮ Java.util - IdentityHashMap