On 7/01/2015 7:45 PM, Remi Forax wrote:
A simple Java question, what this code does ?

   ArrayList<String> list = new ArrayList<>();
   list.add("foo");
   list.add("bar");
   for(String s: list) {
     list.remove(s);
   }

:(

Rémi
tip: the bug lies in ArrayList.Itr.hasNext() (and
AbstractList.Itr.hasNext()).

This is not a bug. The only supported way to remove from a collection you are iterating over is to use an Iterator's remove method.

http://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html#remove--

"The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method."

and as already pointed out the forEach docs make it clear you can't use forEach in such a context as the Iterator is not exposed to you.

So don't do that.

David



Reply via email to