Saturday 30 November 2019

Calling remove in foreach loop in Java





In Java, is it legal to call remove on a collection when iterating through the collection using a foreach loop? For instance:



List names = ....
for (String name : names) {
// Do something
names.remove(name).
}


As an addendum, is it legal to remove items that have not been iterated over yet? For instance,




//Assume that the names list as duplicate entries
List names = ....
for (String name : names) {
// Do something
while (names.remove(name));
}

Answer



To safely remove from a collection while iterating over it you should use an Iterator.




For example:



List names = ....
Iterator i = names.iterator();
while (i.hasNext()) {
String s = i.next(); // must be called before you can call i.remove()
// Do something
i.remove();
}



From the Java Documentation :




The iterators returned by this class's iterator and listIterator
methods are fail-fast: if the list is structurally modified at any
time after the iterator is created, in any way except through the
iterator's own remove or add methods, the iterator will throw a
ConcurrentModificationException. Thus, in the face of concurrent

modification, the iterator fails quickly and cleanly, rather than
risking arbitrary, non-deterministic behavior at an undetermined time
in the future.




Perhaps what is unclear to many novices is the fact that iterating over a list using the for/foreach constructs implicitly creates an iterator which is necessarily inaccessible. This info can be found here


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...