I have a list (List) and I want to index its objects by their ids using a map (HashMap). I always use list.si
The 'capacity' keyword is incorrect by definition and isn't used in the way typically expected.
By default the 'load factor' of a HashMap is 0.75, this means that when the number of entries in a HashMap reaches 75% of the capacity supplied, it will resize the array and rehash.
For example if I do:
Map map = new HashMap<>(100);
When I am adding the 75th entry, the map will resize the Entry table to 2 * map.size() (or 2 * table.length). So we can do a few things:
The best option is the latter of the two, let me explain what's going on here:
list.size() / 0.75
This will return list.size() + 25% of list.size(), for example if my list had a size of 100 it would return 133. We then add 1 to it as the map is resized if the size of it is equal to 75% of the initial capacity, so if we had a list with a size of 100 we would be setting the initial capacity to 134, this would mean that adding all 100 entries from the list would not incur any resize of the map.
End result:
Map map = new HashMap<>(list.size() / 0.75 + 1);