ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# Java - 获取`HashMap`的大小 > 原文: [https://beginnersbook.com/2014/07/java-get-size-of-hashmap-example/](https://beginnersbook.com/2014/07/java-get-size-of-hashmap-example/) 在这个例子中,我们将看到如何使用[`HashMap`类](https://beginnersbook.com/2013/12/hashmap-in-java-with-example/)的`size()`方法获取`HashMap`的大小。方法定义和描述如下: `public int size()`:返回此映射中键 - 值映射的数量。 ```java 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()); } } ``` **输出:** ```java Size of HashMap : 5 ``` 由于我们在`HashMap`中有 5 个键值对,因此`size()`方法返回整数 5。另外,在上面的例子中我们采用了`Integer`键和`String`值,但是如果你想拥有`String`键和`String`值,那么你可以这样改变泛型: `HashMap<String, String> hashmap = new HashMap<String, String>();` 请记住,如果您有字符串键和值,添加这样的对。 `hashmap.put("11", "Value1");`