Best HashMap initial capacity while indexing a List

前端 未结 6 685
小蘑菇
小蘑菇 2021-01-31 16:46

I have a list (List list) and I want to index its objects by their ids using a map (HashMap map). I always use list.si

6条回答
  •  情书的邮戳
    2021-01-31 17:26

    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:

    1. Change the load factor - this could impact the performance of the map
    2. Set the initial capacity to list.size() / 0.75 + 1

    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);
    

提交回复
热议问题