The syntax of the clear()
method is:
hashmap.clear()
Here, hashmap is an object of the HashMap
class.
clear() Parameters
The clear()
method does not take any parameters.
clear() Return Value
The clear()
method does not return any value. Rather, it makes changes to the hashmap.
Example: Java HashMap clear()
import java.util.HashMap;
class Main {
public static void main(String[] args) {
HashMap<String, Integer> numbers = new HashMap<>();
numbers.put("One", 1);
numbers.put("Two", 2);
numbers.put("Three", 3);
System.out.println("HashMap: " + numbers);
// remove all mappings from HashMap
numbers.clear();
System.out.println("HashMap after clear(): " + numbers);
}
}
Output
HashMap: {One=1, Two=2, Three=3} HashMap after clear(): {}
In the above example, we have created a hashmap named numbers. Here, we have used the clear()
method to remove all the key/value pairs from numbers.
Note: We can use the Java HashMap remove() method to remove a single item from the hashmap.
Reinitialize The HashMap
In Java, we can achieve the functionality of the clear()
method by reinitializing the hashmap. For example,
import java.util.HashMap;
class Main {
public static void main(String[] args) {
HashMap<String, Integer> numbers = new HashMap<>();
numbers.put("One", 1);
numbers.put("Two", 2);
numbers.put("Three", 3);
System.out.println("HashMap: " + numbers);
// reinitialize the hashmap
numbers = new HashMap<>();
System.out.println("New HashMap: " + numbers);
}
}
Output
HashMap: {One=1, Two=2, Three=3} New HashMap: {}
In the above example, we have created a hashmap named numbers. The hashmap consists of 3 elements. Notice the line,
numbers = new HashMap<>();
Here, the process doesn't remove all items from the hashmap. Instead, it creates a new hashmap and assigns the newly created hashmap to numbers. And, the older hashmap is removed by Garbage Collector.
Note: It may appear that the reinitialization of HashMap
and the clear()
method is working in similar way. However, they are two different processes.