isEmpty() 方法的语法是:
hashmap.isEmpty()
这里,
hashmap 是
HashMap 类的对象。
isEmpty() 参数
isEmpty() 方法不带任何参数。
isEmpty() 返回值
如果哈希图不包含任何键/值映射,则返回true
如果哈希映射包含键/值映射,则返回false
示例: 检查HashMap是否为空
import java.util.HashMap; class Main { public static void main(String[] args) { // create an HashMap HashMap<String, Integer> languages = new HashMap<>(); System.out.println("Newly Created HashMap: " + languages); // checks if the HashMap has any element boolean result = languages.isEmpty(); // true System.out.println("Is the HashMap empty? " + result); // insert some elements to the HashMap languages.put("Python", 1); languages.put("Java", 14); System.out.println("Updated HashMap: " + languages); // checks if the HashMap is empty result = languages.isEmpty(); // false System.out.println("Is the HashMap empty? " + result); } }
输出
Newly Created HashMap: {}
Is the HashMap empty? true
Updated HashMap: {Java=14, Python=1}
Is the HashMap empty? false
在上面的例子中,我们创建了一个名为
languages 的 hashmap。在这里,我们使用了
isEmpty() 方法来检查 hashmap 是否包含任何元素。
最初,新创建的hashmap不包含任何元素。因此,
isEmpty() 返回
true。但是,在我们添加一些元素(Python、Java)后,该方法返回
false。

