在这个例子中,我们将看到如何使用HashMap类的size()方法获取HashMap的大小。方法定义和描述如下:
public int size():返回此映射中键 – 值映射的数量。
import java.util.HashMap;public class SizeExample { public static void main(String[] args) { // Creating a HashMap of int keys and String values HashMap<Integer, String> hashmap = new HashMap<Integer, String>(); // Adding Key and Value pairs to HashMap hashmap.put(11,"Value1"); hashmap.put(22,"Value2"); hashmap.put(33,"Value3"); hashmap.put(44,"Value4"); hashmap.put(55,"Value5"); // int size() method returns the number of key value pairs System.out.println("Size of HashMap : " + hashmap.size()); }}
输出:
Size of HashMap : 5
由于我们在HashMap中有 5 个键值对,因此size()方法返回整数 5。另外,在上面的例子中我们采用了Integer键和String值,但是如果你想拥有String键和String值,那么你可以这样改变泛型:
HashMap<String, String> hashmap = new HashMap<String, String>();
请记住,如果您有字符串键和值,添加这样的对。
hashmap.put("11", "Value1");
