java.util.ConcurrentModificationException not thrown when expected

前端 未结 2 1405
伪装坚强ぢ
伪装坚强ぢ 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 10:56

    The iterator returned from ArrayList.iterator() in the implementation we're apparently both using only checks for structural modification in calls to next(), not in calls to hasNext(). The latter just looks like this (under Java 8):

    public boolean hasNext() {
        return cursor != size;
    }
    

    So in your second case, the iterator "knows" that it's returned two elements, and that the list only has two elements... so hasNext() just returns false, and we never end up calling next() the third time.

    I would view this as an implementation detail - basically the checking not being as strict as it could be. It would be entirely reasonable for hasNext() to perform a check and throw an exception in this case too.

提交回复
热议问题