Nota: Estou ciente do Iterator#remove()método.
No exemplo de código a seguir, não entendo por que o método List.removein mainé lançado ConcurrentModificationException, mas não no removemétodo
public class RemoveListElementDemo {
private static final List<Integer> integerList;
static {
integerList = new ArrayList<Integer>();
integerList.add(1);
integerList.add(2);
integerList.add(3);
}
public static void remove(Integer toRemove) {
for(Integer integer : integerList) {
if(integer.equals(toRemove)) {
integerList.remove(integer);
}
}
}
public static void main(String... args) {
remove(Integer.valueOf(2));
Integer toRemove = Integer.valueOf(3);
for(Integer integer : integerList) {
if(integer.equals(toRemove)) {
integerList.remove(integer);
}
}
}
}
ConcurrentModificationExceptione o outro não.
return;no loop.
Iterator#remove(). Por que você está fazendo assim?