java.util.ConcurrentModificationException not thrown when expected

前端 未结 2 1403
伪装坚强ぢ
伪装坚强ぢ 2020-12-06 10:50

The following code throws a java.util.ConcurrentModificationException, as expected:

   public void test(){
      ArrayList myList = new ArrayLi         


        
2条回答
  •  抹茶落季
    2020-12-06 11:08

    Note also the last paragraph of the ArrayList documentation summary:

    Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

    If you're worrying about forcing lists to be read-only, use the Collections.unmodifiableList method, instead of checking for ConcurrentModificationException, which as mentioned above is not guaranteed to be thrown in all relevant cases.

提交回复
热议问题