I’ve got an existing ArrayList which will be filtered according to certain criteria. I’m using Apache’s CollectionUtils.select(Collection, Predicate, Collection) for filtering.
The second collection which is passed to this method will be populated with the relevant objects. Is it now more wise to create this new collection with
List newList = new ArrayList();
or with
List newList = new ArrayList(listToBeFiltered.size());
?
In the first case, the List will be upsized if the initial capacity is reached, while in the second case sometimes a way too big List will be created.
Which way is the better one? And please correct me if I’ve made any mistakes in my explanation.
That normally depends on the final size and the size of the collection to be filtered.
Resizing an
ArrayListor normally done by doubling the current size and copying the content around. Thus with a huge final size there might be couple of resize operations needed.On the other hand a really large initial size might eat up quite a lot of memory and might trigger garbage collection earler, but the list would have to be really big.
You might try and profile both options but for standard sizes I’d prefer specifying a sensible initial size.