在 Java 中检查 HashMap 是否为空


使用 isEmpty() 方法来检查 HashMap 是否为空。我们首先创建 HashMap −

HashMap hm = new HashMap();

现在,添加一些元素 −

hm.put("Bag", new Integer(1100));
hm.put("Wallet", new Integer(700));
hm.put("Belt", new Integer(600));

由于我们上面已经添加了元素,因此 HashMap 并不为空。让我们来检查一下 −

set.isEmpty()

下面是一个检查 HashMap 是否为空的示例 −

示例

 在线演示

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      // Create a hash map
      HashMap hm = new HashMap();
      // Put elements to the map
      hm.put("Bag", new Integer(1100));
      hm.put("Wallet", new Integer(700));
      hm.put("Belt", new Integer(600));
      // Get a set of the entries
      Set set = hm.entrySet();
      // Get an iterator
      Iterator i = set.iterator();
      // Display elements
      while(i.hasNext()) {
         Map.Entry me = (Map.Entry)i.next();
         System.out.print(me.getKey() + ": ");
         System.out.println(me.getValue());
      }
      System.out.println();
      System.out.println("Is the HashMap with empty elements? "+set.isEmpty());
   }
}

输出

Belt: 600
Wallet: 700
Bag: 1100
Is the HashMap with empty elements? False

更新于: 30-Jul-2019

506 次浏览

启动你的职业生涯

完成课程,获得认证

开始
广告
© . All rights reserved.