Java HashMap isEmpty() Method
The isEmpty() method is used to check whether the HashMap is empty.
The syntax of the isEmpty() method is:
hashmap.isEmpty()
Note:hashmap is an object of the HashMap class.
Parameter Description:
- None
Return Value
Returns true if the HashMap does not contain any key/value pair mappings, otherwise returns false.
Example
The following example demonstrates the use of the isEmpty() method:
Example
import java.util.HashMap;
class Main {
public static void main(String[] args) {
HashMap<Integer, String> sites = new HashMap<>();
// Check whether the HashMap contains elements
boolean result = sites.isEmpty(); // true
System.out.println("Is it empty? " + result);
// Add some elements to the HashMap
sites.put(1, "Google");
sites.put(2, "Example");
sites.put(3, "Taobao");
System.out.println("HashMap: " + sites);
result = sites.isEmpty(); // false
System.out.println("Is it empty? " + result);
}
}
class Main {
public static void main(String[] args) {
HashMap<Integer, String> sites = new HashMap<>();
// Check whether the HashMap contains elements
boolean result = sites.isEmpty(); // true
System.out.println("Is it empty? " + result);
// Add some elements to the HashMap
sites.put(1, "Google");
sites.put(2, "Example");
sites.put(3, "Taobao");
System.out.println("HashMap: " + sites);
result = sites.isEmpty(); // false
System.out.println("Is it empty? " + result);
}
}
Executing the above program produces the output:
是否为空? true
HashMap: {1=Google, 2=Example, 3=Taobao}
是否为空? false
In the above example, we created a HashMap named sites, and later in the code we used the isEmpty() method to check whether it is empty.
Other Extensions
Java HashMap