I know that removing an element from a list while iterating it is not recommended.
You better use iterator.remove(), java streams, or copy the remove to an external list.
But this simple code just works:
static List<Integer> list = new ArrayList<Integer>();
...
private static void removeForI() {
for (int i = 0; i < 10; i++) {
if (i == 3) {
list.remove(i);
continue;
}
System.out.println(i);
}
}
Is it safe to use it?
i, not the element at indexi. Result is that 4th element is removed from list, and that code prints0 1 2 4 5 6 7 8 9, skipping the number3, but not skipping any element.Iteratorimplementation throws aConcurrentModifcationExceptionif you iterate over it and modify the underlying collection.