I have quite large List named items (>= 1,000,000 items) and some condition denoted by
I would make a new List
to add the items to, since removing an item from the middle of a List is quite expensive.
public static List removeMany(List items) {
List tempList = new ArrayList(items.size()/2); //if about half the elements are going to be removed
Iterator iter = items.iterator();
while (item : items) {
// goes here
if (/*: */i % 2 != 0) {
tempList.add(item);
}
}
return tempList;
}
EDIT: I haven't tested this, so there may very well be small syntax errors.
Second EDIT: Using a LinkedList
is better when you don't need random access but fast add times.
BUT...
The constant factor for ArrayList
is smaller than that for LinkedList
(Ref). Since you can make a reasonable guess of how many elements will be removed (you said "about half" in your question), adding an element to the end of an ArrayList
is O(1) as long as you don't have to re-allocate it. So, if you can make a reasonable guess, I would expect the ArrayList
to be marginally faster than the LinkedList
in most cases. (This applies to the code I have posted. In your naive implementatation, I think LinkedList
will be faster).