1. Introduction
The HashMap class in Java, part of the java.util package, stores key-value pairs. To determine if a HashMap instance is empty, we can use the isEmpty() method. This method returns a boolean value: true if the map contains no key-value mappings, and false otherwise. In this post, we will create a simple program demonstrating the use of the isEmpty() method.
2. Program Steps
1. Create a HashMap and check if it is empty using the isEmpty() method.
2. Populate the HashMap with some key-value pairs.
3. Again, check if the updated HashMap is empty using the isEmpty() method.
3. Code Program
import java.util.HashMap;
import java.util.Map;
public class HashMapIsEmpty {
public static void main(String[] args) {
// Step 1: Create a HashMap and check if it is empty
Map<String, Integer> map = new HashMap<>();
System.out.println("Is the HashMap empty? " + map.isEmpty());
// Step 2: Populate the HashMap with some key-value pairs
map.put("One", 1);
map.put("Two", 2);
map.put("Three", 3);
// Step 3: Again, check if the updated HashMap is empty
System.out.println("Is the updated HashMap empty? " + map.isEmpty());
}
}
Output:
Is the HashMap empty? true Is the updated HashMap empty? false
4. Step By Step Explanation
Step 1: A HashMap named map is created. Initially, it has no key-value pairs. The isEmpty() method is called to check whether map is empty, which returns true.
Step 2: We add three key-value pairs to the HashMap. Now, map is no longer empty.
Step 3: We again check if map is empty using the isEmpty() method. This time, it returns false as there are key-value pairs present in the HashMap.