HashMap clear() in Java

clear(): This method is available in java.util.HashMap class of Java.

Syntax:

void java.util.HashMap.clear()

This method removes all of the mappings from this map. The map will be empty after this call returns.

Parameters: NA

Returns: NA

Exceptions: NA

Approach

Java

import java.util.HashMap;

public class HashMapclear {
    public static void main(String[] args) {
        HashMap<String, Integer> hashMap = new
HashMap<String, Integer>();

        hashMap.put("Hello", 1);
        hashMap.put("World", 2);

        System.out.println("Map elements before clear: " +
hashMap);
        hashMap.clear();
        System.out.println("Map elements after clear: " +
hashMap);
    }
}

Output:

Map elements before clear: {Hello=1, World=2}

Map elements after clear: {}


No comments:

Post a Comment