在 Java 中查詢 HashMap 的大小
使用 size() 方法獲取 HashMap 的大小。我們先建立一個 HashMap
HashMap hm = new HashMap();
現在,新增一些元素 -
hm.put("Bag", new Integer(1100));
hm.put("Sunglasses", new Integer(2000));
hm.put("Franes", new Integer(800));
hm.put("Wallet", new Integer(700));
hm.put("Belt", new Integer(600));由於我們上面添加了 5 個元素,因此,size() 方法將給出 5 作為結果 -
set.size()
以下是如何查詢 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("Sunglasses", new Integer(2000));
hm.put("Franes", new Integer(800));
hm.put("Wallet", new Integer(700));
hm.put("Belt", new Integer(600));
Set set = hm.entrySet();
System.out.println("Elements in HashMap...");
// 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("Size of HashMap = "+set.size());
}
}輸出
Elements in HashMap... Franes: 800 Belt: 600 Wallet: 700 Bag: 1100 Sunglasses: 2000 Size of HashMap = 5
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP