在Java中获取HashMap的大小的例子

150 阅读1分钟

在这个例子中,我们将看到如何使用HashMap类的size()方法获得HashMap的大小。

根据Oracle文档size()方法返回映射中存在的键值映射的数量。
同时阅读 : 检查HashMap中是否存在某个特定的值

size()方法的语法 方法的语法 的语法如下。

public int size()

参数。

size()方法不接受任何参数。

返回。

size()方法返回map的大小,换句话说,map中存在的键值对的数量。

获取HashMap的大小 例子

1.带有整数键和字符串值的HashMap

import java.util.*; public class HashMapSizeExample { public static void main(String args[]) { // Creating HashMap object with Integer keys and String values HashMap<Integer,String> map = new HashMap<>(); // Adding elements to the HashMap object map.put(1, "CocoCola"); map.put(2, "Pepsi"); map.put(3, "Thums Up"); map.put(4, "Fanta"); // Calculating the size of the HashMap using size() method System.out.println(" Size of the given HashMap is: "+ map.size()); } }

输出:
给定的HashMap的大小是。4

解释

size()方法返回4,因为我们在HashMap中有4个键值映射。在上面的例子中,我们展示了整数键和字符串值,但是如果你想要字符串键和字符串值,你可以改变语法如下。

HashMap<String,String> map = new HashMap<>();

2.带有字符串键和整数值的HashMap

import java.util.*; public class HashMapSizeExample2 { public static void main(String args[]) { // Creating HashMap object with String keys and Integer values HashMap<String, Integer> map2 = new HashMap<>(); // Putting elements to the HashMap object map2.put("Java", 10); map2.put("Hungry", 20); map2.put("Blog", 30); // Finding the size of the HashMap using size() method System.out.println(" Size of the given HashMap is: "+ map2.size()); } }

输出:
给定的HashMap的大小为:3

解释

我们在HashMap中有3个键值对,这就是为什么size()方法返回3。在上面的例子中,我们计算了带有字符串键和整数值的HashMap的大小。

今天就讲到这里。如果你对如何用Java获得HashMap的大小有任何疑问,请在评论中提及。