📜  Java HashMap isEmpty()

📅  最后修改于: 2020-09-27 00:42:55             🧑  作者: Mango

Java HashMap的isEmpty()方法检查哈希图是否为空。

isEmpty()方法的语法为:

hashmap.isEmpty()

在这里, hashmapHashMap类的对象。


isEmpty()参数

isEmpty()方法不带任何参数。


isEmpty()返回值
  • 如果哈希图不包含任何键/值映射,则返回true
  • 如果哈希图包含键/值映射,则返回false

示例:检查HashMap是否为空
import java.util.HashMap;

class Main {
    public static void main(String[] args) {
        // create an HashMap
        HashMap 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

在上面的示例中,我们创建了一个名为language的哈希表。在这里,我们使用了isEmpty()方法来检查哈希图是否包含任何元素。

最初,新创建的哈希图不包含任何元素。因此, isEmpty()返回true 。但是,在我们添加了一些元素( PythonJava )之后,该方法返回false