Your condition is somewhat simplistic, as you could simply use aList.remove("Orange")
resp. aList.removeAll(Collections.singleton("Orange"))
instead, but there is an alternative with internal iteration which also works with more complex conditions, aList.removeIf(str -> str.equals("Orange"))
.
In case of ArrayList
, this will immediately show the advantage of internal iteration: in case of calling remove()
on an Iterator
, the ArrayList
has no control over the loop, hence doesn’t know when you exit it resp. abandon the Iterator
. You can access the list through the List
interface at any time, reading and continue iterating or writing and not iterating further.
So every time you invoke remove()
, the list has to be brought into a consistent state, i.e. all subsequent elements have to be copied at the right place when removing an element. This gives iterating and removing from an ArrayList
a worst case of O(n2)
time complexity.
In contrast, the removeIf
method only has to provide a completed state of the List
when the method returns. Hence, it may postpone copying elements to the point when the final position is known, which makes it an O(n)
operation. So, for large lists, there’s a significant performance advantage.
Generally, methods with internal iterations provide the possibility of being implemented optimized for the particular internal data structure, while never being worse than the external loop, as the iterator based loop is the fallback of these methods anyway.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…