117. Handling map capacity
Let’s assume that we need a List
capable of holding 260 items. We can do it as follows:
List<String> list = new ArrayList<>(260);
The array underlying ArrayList
is created directly to accommodate 260 items. In other words, we can insert 260 items without worrying about resizing or enlarging the list several times in order to hold these 260 items.
Following this logic, we can reproduce it for a map as well:
Map<Integer, String> map = new HashMap<>(260);
So, now we can assume that we have a map capable of accommodating 260 mappings. Actually, no, this assumption is not true! A HashMap
works on the hashing principle and is initialized with an initial capacity (16 if no explicit initial capacity is provided) representing the number of internal buckets and a default load factor of 0.75. What does that mean? It means that when a HashMap
reaches 75% of its current capacity, it is doubled in size and a rehashing...