Java HashMap clear() Method

Java HashMap Java HashMap

The clear() method is used to delete all key/value pairs in the specified HashMap.

The syntax of the clear() method is:

hashmap.clear()

Note:hashmap is an object of the HashMap class.

Parameter Description:

  • None

Return Value

No return value.

Example

The following example demonstrates the use of the clear() method:

Example

import java.util.HashMap;

class Main {
    public static void main(String[] args) {

        HashMap<Integer, String> sites = new HashMap<>();
        sites.put(1, "Google");
        sites.put(2, "Example");
        sites.put(3, "Taobao");
        System.out.println("HashMap: " + sites);

        // Delete all mappings from the HashMap
        sites.clear();
        System.out.println("After using clear() method: " + sites);
    }
}

Executing the above program outputs the result:

HashMap: {1=Google, 2=Example, 3=Taobao}
使用 clear() 方法后: {}

In the above example, we created a HashMap named sites, and later in the code we used the clear() method to delete all key/value pairs of sites.

Note: We can also useJava HashMap remove() Methodto delete the key-value pair corresponding to the key.

Reinitialize HashMap

In Java, we can also delete all key/value pairs by reinitializing the HashMap, for example:

Example

import java.util.HashMap;

class Main {
    public static void main(String[] args) {

        HashMap<Integer, String> sites = new HashMap<>();
        sites.put(1, "Google");
        sites.put(2, "Example");
        sites.put(3, "Taobao");
        System.out.println("HashMap: " + sites);

        // Delete all mappings from the HashMap
        // Reinitialize hashmap
        sites = new HashMap<>();
        System.out.println("New HashMap: " + sites);
    }
}

Executing the above program outputs the result:

HashMap: {1=Google, 2=Example, 3=Taobao}
新的 HashMap: {}

In the above example, we created a HashMap named sites, which contains 3 elements. Note this line:

numbers = new HashMap<>();

The above code does not delete all items from the HashMap; it creates a new HashMap and assigns it to sites. The original key-value pairs of sites will be reclaimed and deleted by the garbage collector.

Java HashMap Java HashMap

Other Extensions