How to initialize the size of a map in Java?
In Java, you can initialize the size of a Map using the following methods:
- By using a constructor, it is possible to specify the initial capacity size when creating a Map object. For example:
Map<String, Integer> map = new HashMap<>(10); // 初始化HashMap的初始容量为10
- By using the putAll method, you can first create an empty Map with the desired size, and then add the elements of another Map to it using putAll method. For example:
Map<String, Integer> map1 = new HashMap<>();
map1.put("key1", 1);
map1.put("key2", 2);
// 初始化一个具有与map1相同大小的空Map
Map<String, Integer> map2 = new HashMap<>(map1.size());
// 将map1的元素添加到map2中
map2.putAll(map1);
Please note that even if an initial capacity size is specified, the actual capacity of a Map will still be dynamically adjusted as needed. Therefore, there is no need to worry too much about the accuracy of the capacity, as Java’s Map implementation will handle it automatically.