Wednesday, December 7, 2016

Iterating through a Collection, avoiding ConcurrentModificationException when removing in loop

Iterator.remove() is safe, you can use it like this:
List<String> list = new ArrayList<>();

// This is a clever way to create the iterator and call iterator.hasNext() like
// you would do in a while-loop. It would be the same as doing:
//     Iterator<String> iterator = list.iterator();
//     while (iterator.hasNext()) {
for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
    String string = iterator.next();
    if (string.isEmpty()) {
        // Remove the current element from the iterator and the list.
        iterator.remove();
    }
}
Note that Iterator.remove is the only safe way to modify a collection during iteration; the behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress.
Source:
http://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html
----------------------------------------------------------------------
Use an Iterator and call remove():
Iterator<String> iter = myArrayList.iterator();

while (iter.hasNext()) {
    String str = iter.next();

    if (someCondition)
        iter.remove();
}

No comments:

Post a Comment