The implementation of the addAll method in java.util.Collections simply loops through the source collection and calls the add method of the receiving collection for each element in the source collection.
Thus, resizing of the receiving collection’s underlying data structure could occur multiple times if the capacity of the receiving collection is small and we are adding many elements to it. Each resize will be an O(n) operation.
It seems that a good collections addAll method should exist that will check the number of elements we will be adding and set the capacity of the receiving collection once at the beginning (if necessary). Does such a utility method exist? And if not, why not?
Clarification: I realize that there are implementation specific addAll methods (as in ArrayList) that have this desired behavior. I am wondering if there are Collection utility classes that will get me this behavior in a way that works across all Collection implementation classes.
Such a utility method cannot exists for a generic
Collection, because the necessary methodensureCapacity(int)is not in any interface but only on implementations which have some benefit for that. Currently this areArrayList,BitSetandVector. BothArrayListandVectorhave adjustedaddAllmethods.BitSetis something completely different 🙂