I am traversing a list and want to remove a certain element that matches a condition. I also want to return that element. There are two ways I've come up with to do this.
First:
for (int i = 0; i < list.size(); i++) {
if (shouldBeRemoved(list.get(i)) {
E toRemove = list.get(i);
list.remove(i);
return toRemove;
}
}
return null;
Second:
Iterator<E> iterator = list.iterator();
while (iterator.hasNext()) {
E element = iterator.next();
if (shouldBeRemoved(element)) {
iterator.remove();
return element;
}
}
return null;
I like the Iterator method, since it seems like the Iterator "knows where it is" and therefore shouldn't have to go through the list to find the thing to delete; the going-through happens alongside the search for the item itself. That's just speculation, though.
Which one of these is more efficient/faster? Are there certain scenarios in which it is better to use one or the other?
EDIT: The intended behavior is for only one element to be removed. The specific element that is to be removed doesn't matter, as long as it matches the condition.
As a programmer, I know the specific implementation of List that is being used, but for the purposes of this question, I'd like to examine the performance of multiple different implementations, if it is relevant to the performance of the algorithm.
Which one of these is more efficient/faster? Are there certain scenarios in which it is better to use one or the other?
They are about the same (and could be made slightly more so) for a random-access list such as an ArrayList
, but the iterator-based solution is much more efficient for a sequential list, such as a LinkedList
.
This is because in a sequential list, each get()
and each remove()
needs to start at the beginning of the list and iterate through it to the specified index, so you have that iteration happening at least twice for each element to be removed (three times in the actual implementation you present). On the other hand, the Iterator
approach iterates through the whole list exactly once, no matter what specific type of list or how many elements are selected for removal. Even if zero elements are removed, you can at best match that with an index-based approach.
In view of that, the Iterator
-based approach is probably to be preferred unless you have more specific information about what type of List
you can expect, reflected in the declared type of list
.