size()
方法的语法是:
hashmap.size()
这里,
hashmap 是
HashMap
类的对象。
size() 参数
size()
方法不带任何参数。
size() 返回值
返回哈希图中存在的键/值映射的数量示例: Java HashMap size()
import java.util.HashMap; class Main { public static void main(String[] args) { // create an HashMap HashMap<String, String> countries = new HashMap<>(); // insert keys/values to the HashMap countries.put("USA", "Washington"); countries.put("UK", "London"); countries.put("Canada", "Ottawa"); System.out.println("HashMap: " + countries); // get the number of keys/values from HashMap int size = countries.size(); System.out.println("Size of HashMap: " + size); } }
输出
HashMap: {Canada=Ottawa, USA=Washington, UK=London} Size of HashMap: 3
在上面的例子中,我们创建了一个名为
countries 的哈希映射。在这里,我们使用了
size()
方法来获取哈希图中存在的 键/值映射的数量。