Why am I not getting a java.util.ConcurrentModificationException in this example?

后端 未结 10 2104
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 07:59

Note: I am aware of the Iterator#remove() method.

In the following code sample, I don\'t understand why the List.remove in main

10条回答
  •  盖世英雄少女心
    2020-11-22 08:37

    This snippet will always throw a ConcurrentModificationException.

    The rule is "You may not modify (add or remove elements from the list) while iterating over it using an Iterator (which happens when you use a for-each loop)".

    JavaDocs:

    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.

    Hence if you want to modify the list (or any collection in general), use iterator, because then it is aware of the modifications and hence those will be handled properly.

    Hope this helps.

提交回复
热议问题