HashMap isEmpty() Method in Java
The isEmpty() method of HashMap checks if the map contains any key/value pairs. It returns true if the map does not contain any entries.
More formally, it returns true if the size of the HashMap is equal to zero. If the size of the HashMap is greater than zero then the isEmpty() method returns false.
Method Signature
public boolean isEmpty()
Parameters
It does not accept any parameters.
Returns
boolean i.e true when HashMap is empty, otherwise false.
Program
import java.util.HashMap; import java.util.Map; // This program shows // how to use isEmpty() method // to check if the HashMap is empty or not public class HashMapIsEmpty { public static void main(String[] args) { // Create a HashMap Mapmap = new HashMap(); // Put entries into the HashMap map.put(101, "John"); map.put(102, "Adam"); map.put(103, "Ricky"); map.put(104, "Chris"); // Print the elements System.out.println("HashMap elements : " + map); // At this point, HashMap has entries in it // Hence isEmpty() returns false System.out.println("Is HashMap empty? : " + map.isEmpty()); // Clear the HashMap map.clear(); // HashMap doesn't have entries now System.out.println("HashMap elements after clear : " + map); // isEmpty() returns true System.out.println("Is HashMap empty? : " + map.isEmpty()); } }
Output
HashMap elements : {101=John, 102=Adam, 103=Ricky, 104=Chris} Is HashMap empty? : false HashMap elements after clear : {} Is HashMap empty? : true
Explanation
- Create an instance of HashMap
- Add entries into it
- Call isEmpty() to check if the entries are present. Here isEmpty() returns false
- Clear the HashMap using the clear() method
- At this point, the size of HashMap is equal to zero. Therefore, call to isEmpty() returns true
0 Comments