在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[]) {
      //创建一个哈希映射
      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));
      Set set = hm.entrySet();
      System.out.println("Elements in HashMap...");
      //获取一个迭代器
      Iterator i = set.iterator();
      //显示元素
      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