リストでは、追加または削除は変更と見なされます。あなたの場合、5 つの変更 (追加) を行いました。
「for each」ループは次のように機能します。
1.It gets the iterator.
2.Checks for hasNext().
public boolean hasNext()
{
return cursor != size(); // cursor is zero initially.
}
3. true の場合、next() を使用して次の要素を取得します。
public E next()
{
checkForComodification();
try {
E next = get(cursor);
lastRet = cursor++;
return next;
} catch (IndexOutOfBoundsException e) {
checkForComodification();
throw new NoSuchElementException();
}
}
final void checkForComodification()
{
// Initially modCount = expectedModCount (our case 5)
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
hasNext() が false を返すまで、ステップ 2 と 3 を繰り返します。
リストから要素を削除すると、サイズが縮小され、modCount が増加します。
反復中に要素を削除すると、 modCount != expectedModCount が満たされ、 ConcurrentModificationException がスローされます。
しかし、最後から 2 番目のオブジェクトを削除するのは奇妙です。あなたのケースでどのように機能するか見てみましょう。
当初、
カーソル = 0 サイズ = 5 --> hasNext() が成功し、next() も例外なく成功します。
カーソル = 1 サイズ = 5 --> hasNext() が成功し、next() も例外なく成功します。
カーソル = 2 サイズ = 5 --> hasNext() が成功し、next() も例外なく成功します。
カーソル = 3 サイズ = 5 --> hasNext() が成功し、next() も例外なく成功します。
あなたの場合、 'd' を削除すると、サイズが 4 に縮小されます。
カーソル = 4 サイズ = 4 --> hasNext() は成功せず、next() はスキップされます。
それ以外の場合は、modCount != expectedModCount として ConcurrentModificationException がスローされます。
この場合、このチェックは行われません。
反復中に要素を印刷しようとすると、4 つのエントリのみが印刷されます。最後の要素はスキップされます。
私が明らかにしたことを願っています。