-1
を削除してArrayList
を空にするとConcurrentModificationException
を投げ、同じ空から0
を取り除くとArrayList
はNoSuchElementException
を投げます。ArrayList remove()の特有の動作 - なぜですか?
以下のコード見つけてください:私の理解NoSuchElementException
から
public class Test {
public static void main(String[] argv) {
ArrayList<Integer> list = new ArrayList<Integer>();
Iterator<Integer> it = list.iterator();
try {
list.remove(-1);
} catch (IndexOutOfBoundsException e) {
}
try {
it.next();// Throwing ConcurrentModificationException
} catch (ConcurrentModificationException e) {
System.err.println("ConcurrentModificationException 1");
} catch (NoSuchElementException e) {
System.err.println("NoSuchElementException 1 ");
}
list = new ArrayList<Integer>();
it = list.iterator();
try {
list.remove(0);
} catch (IndexOutOfBoundsException e) {
}
try {
it.next();// Throwing NoSuchElementException
} catch (NoSuchElementException e) {
System.err.println("NoSuchElementException 2");
} catch (ConcurrentModificationException e) {
System.err.println("ConcurrentModificationException 2 ");
}
}
}
は結構ですが、なぜConcurrentModificationException
がスローされますか?
これはイテレータの動作です。リストを変更すると、リストが呼び出されます。イテレータはCMEをスローします。私が疑う呼び出しの違いは、 'list.remove(0)'と 'list.remove(-1)'とで何が起こるかということです。 – matt