在 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