AFAIK, there are two approaches:
- Iterate over a copy of the collection
- Use the iterator of the actual collection
For instance,
List<Foo> fooListCopy = new ArrayList<Foo>(fooList);
for(Foo foo : fooListCopy){
// modify actual fooList
}
and
Iterator<Foo> itr = fooList.iterator();
while(itr.hasNext()){
// modify actual fooList using itr.remove()
}
Are there any reasons to prefer one approach over the other (e.g. preferring the first approach for the simple reason of readability)?
You can't do the second, because even if you use the
remove()
method on Iterator, you'll get an Exception thrown.Personally, I would prefer the first for all
Collection
instances, despite the additional overheard of creating the newCollection
, I find it less prone to error during edit by other developers. On some Collection implementations, the Iteratorremove()
is supported, on other it isn't. You can read more in the docs for Iterator.The third alternative, is to create a new
Collection
, iterate over the original, and add all the members of the firstCollection
to the secondCollection
that are not up for deletion. Depending on the size of theCollection
and the number of deletes, this could significantly save on memory, when compared to the first approach.Let me give a few examples with some alternatives to avoid a
ConcurrentModificationException
.Suppose we have the following collection of books
Collect and Remove
The first technique consists in collecting all the objects that we want to delete (e.g. using an enhanced for loop) and after we finish iterating, we remove all found objects.
This is supposing that the operation you want to do is "delete".
If you want to "add" this approach would also work, but I would assume you would iterate over a different collection to determine what elements you want to add to a second collection and then issue an
addAll
method at the end.Using ListIterator
If you are working with lists, another technique consists in using a
ListIterator
which has support for removal and addition of items during the iteration itself.Again, I used the "remove" method in the example above which is what your question seemed to imply, but you may also use its
add
method to add new elements during iteration.Using JDK 8
For those working with Java 8 or superior versions, there are a couple of other techniques you could use to take advantage of it.
You could use the new
removeIf
method in theCollection
base class:Or use the new stream API:
In this last case, to filter elements out of a collection, you reassign the original reference to the filtered collection (i.e.
books = filtered
) or used the filtered collection toremoveAll
the found elements from the original collection (i.e.books.removeAll(filtered)
).Use Sublist or Subset
There are other alternatives as well. If the list is sorted, and you want to remove consecutive elements you can create a sublist and then clear it:
Since the sublist is backed by the original list this would be an efficient way of removing this subcollection of elements.
Something similar could be achieved with sorted sets using
NavigableSet.subSet
method, or any of the slicing methods offered there.Considerations:
What method you use might depend on what you are intending to do
removeAl
technique works with any Collection (Collection, List, Set, etc).ListIterator
technique obviously only works with lists, provided that their givenListIterator
implementation offers support for add and remove operations.Iterator
approach would work with any type of collection, but it only supports remove operations.ListIterator
/Iterator
approach the obvious advantage is not having to copy anything since we remove as we iterate. So, this is very efficient.removeAll
approach the disadvantage is that we have to iterate twice. First we iterate in the foor-loop looking for an object that matches our removal criteria, and once we have found it, we ask to remove it from the original collection, which would imply a second iteration work to look for this item in order to remove it.Iterator
interface is marked as "optional" in Javadocs, which means that there could beIterator
implementations that throwUnsupportedOperationException
if we invoke the remove method. As such, I'd say this approach is less safe than others if we cannot guarantee the iterator support for removal of elements.There is also a simple solution to "iterate" a
Collection
and removing each items.It simply conciste on looping until the list is empty, and on each iteration, we remove the first element with
remove(0)
.I don't believe this has any improvement compare to the
Iterator
, it still required to have a mutable list but I like the simplicity of this solution.Only second approach will work. You can modify collection during iteration using
iterator.remove()
only. All other attempts will causeConcurrentModificationException
.The first approach will work, but has the obvious overhead of copying the list.
The second approach will not work because many containers don't permit modification during iteration. This includes
ArrayList
.If the only modification is to remove the current element, you can make the second approach work by using
itr.remove()
(that is, use the iterator'sremove()
method, not the container's). This would be my preferred method for iterators that supportremove()
.I would choose the second as you don't have to do a copy of the memory and the Iterator works faster. So you save memory and time.