I have an ArrayList, and I need to filter it (only to remove some elements).
I can’t modify the original list.
What is my best option regarding performances :
- Recreate another list from the original one, and remove items from it :
code :
List<Foo> newList = new ArrayList<Foo>(initialList);
for (Foo item : initialList) {
if (...) {
newList.remove(item);
}
}
- Create an empty list, and add items :
code :
List<Foo> newList = new ArrayList<Foo>(initialList.size());
for (Foo item : initialList) {
if (...) {
newList.add(item);
}
}
Which of these options is the best ? Should I use anything else than ArrayList ? (I can’t change the type of the original list though)
As a side note, approximatively 80% of the items will be kept in the list. The list contains from 1 to around 20 elements.
Since I’m only get suggestions here, I decided to run my own bench to be sure.
Here are the conclusions (with an
ArrayListofString).Solution 1, remove items from the copy : 2400 ms.
Solution 2, create an empty list and fill it : 1600 ms.
newList = new ArrayList<Foo>();Solution 3, same as 2, except you set the initial size of the List : 1530 ms.
newList = new ArrayList<Foo>(initialList.size());Solution 4, same as 2, except you set the initial size of the List + 1 : 1500 ms.
newList = new ArrayList<Foo>(initialList.size() + 1);(as explained by @Soronthar)Source : http://pastebin.com/c2C5c9Ha