I need to delete some objects from an ArrayList if they meet a condition and I\'m wondering which way could be more efficient.
Here\'s the situation: I
There is a hidden cost in removing elements from an ArrayList. Each time you delete an element, you need to move the elements to fill the "hole". On average, this will take N / 2 assignments for a list with N elements.
So removing M elements from an N element ArrayList is O(M * N) on average. An O(N) solution involves creating a new list. For example.
List data = ...;
List newData = new ArrayList(data.size());
for (Iterator i = data.iterator(); i.hasNext(); ) {
Object element = i.next();
if ((...)) {
newData.add(element);
}
}
If N is large, my guess is that this approach will be faster than the remove approach for values of M as small as 3 or 4.
But it is important to create newList large enough to hold all elements in list to avoid copying the backing array when it is expanded.