HashMap clear() Method in Java
The clear() method of HashMap removes all the mappings from the map. After a call to the clear method, the HashMap becomes empty and the size of a map effectively becomes zero.
There is no way to get back the elements once the clear operation is complete. This method is useful when you want to remove all the elements at once.
The clear() method enables users to reuse the same instance of HashMap multiple times.
Some implementations of Map don’t support this method.
Method Signature
public void clear()
Parameters
It does not accept any parameter.
Return Value
It does not return any value.
Program
import java.util.HashMap; import java.util.Map; // This program shows // how to remove all the entries // using clear method public class HashMapClear { public static void main(String[] args) { // Create a HashMap Mapmap = new HashMap(); // Add elements to the map map.put(101, "John"); map.put(102, "Adam"); map.put(103, "Ricky"); map.put(104, "Chris"); System.out.println("Size of map : " + map.size()); System.out.println("Map elements : " + map); // Clear all mappings map.clear(); System.out.println("Size of map after a call to clear : " + map.size()); System.out.println("Map elements after clear: " + map); } }
Output
Size of map : 4 Map elements : {101=John, 102=Adam, 103=Ricky, 104=Chris} Size of map after a call to clear : 0 Map elements after clear: {}
Explanation
- Create a new instance of a HashMap
- Add elements to it, at this point the size is greater than zero
- Call clear() method
- At this point, there are no elements in the map and the size becomes zero
- Before calling the clear() method, please ensure that you never want to access those elements
0 Comments