在 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
廣告