Java

Java

Made by DeepSource

Iterators should not be invalidated while in scope JAVA-E1085

Bug risk
Major

Collections should not be modified when an iterator is still in scope.

If a collection is modified while there is an iterator for that collection in scope, it is possible that inconsistencies could be introduced, leading to bugs. Depending on the context and the collection being used, such code can also result in a ConcurrentModificationException being thrown. It is thus highly recommended that you avoid any structural modification in a collection while any of its iterators are still in scope.

Bad Practice

Iterator<String> it = listOfStrings.iterator();
listOfStrings.clear();

String first = it.next(); // Will throw an ConcurrentModificationException!

Consider avoiding operations that add, remove, or replace elements in a collection until all its iterators go out of scope.

Recommended

Iterator<String> it = listOfStrings.iterator();
// use of the iterator follows
}

References