Performance: Creating an ArrayList from HashMap.values()

后端 未结 5 1368
感动是毒
感动是毒 2021-02-12 10:32

Question is how much it costs to create an ArrayList from a HashMap.values() Collection? Or creating the values Collection alone? Assuming Map.size() > 100k. Objects could also

5条回答
  •  清歌不尽
    2021-02-12 11:03

    HashMap.values() doesn't return an ArrayList of values but a Values Collection.

    Source:

     public Collection values() {
            Collection vs = values;
            return (vs != null ? vs : (values = new Values()));
        }
    

    Values is an AbstractCollection. The reason for values is just to reference HashMap's iterator.

    Your question:

    Question is how much it costs to create an ArrayList from a HashMap.values() Collection?

    That's a linear complexity (as Bozho said) since

    ArrayList valuesList = new ArrayList(hashMap.values());
    

    the ArrayList, valuesList calls the collection hashMap toArray() method which essentially does a for loop from 0..N (size) element in the collection.

    Hope this helps.

提交回复
热议问题