Java HashMap isEmpty()

isEmpty() 方法的语法是:

hashmap.isEmpty()

在这里,hashmapHashMap 类的一个对象


isEmpty() 参数

isEmpty()方法不接受任何参数。


isEmpty()返回值

  • 如果 hashmap 不包含任何 **键/值映射**,则返回 true
  • 如果 hashmap 包含 **键/值映射**,则返回 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


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战