我正在使用以下代码循环遍历一个数组列表,然后从数组列表中删除一个元素。
在这里,我期望会出现ConcurrentModificationException异常。但是没有得到这个异常,特别是当你用(n-1)th元素检查条件时。请帮帮我。下面是我的代码。
在这里,我期望会出现ConcurrentModificationException异常。但是没有得到这个异常,特别是当你用(n-1)th元素检查条件时。请帮帮我。下面是我的代码。
ArrayList<Integer> arrayList = new ArrayList<Integer>();
for (int i = 1; i <= 10; i++) {
arrayList.add(5 * i);
}
System.out.println(arrayList);
Iterator<Integer> iterator = arrayList.iterator();
while (iterator.hasNext()) {
Integer temp = iterator.next();
if (temp == 45) {
/**
* temp == 40 (then i'm getting *ConcurrentModificationException) why not i'm
* getting ConcurrentModificationException if (temp == 45)
*/
arrayList.remove(1);
}
}
System.out.println(arrayList);
提前致谢
iterator.remove();
来替代抛出异常。 - Another coder