List<Integer> list = new ArrayList<Integer>();
list.add(new Integer(0));
list.add(new Integer(1));
list.add(new Integer(2));
list.add(new Integer(3));
System.out.println(list);
for (Integer i : list) {
System.out.println(i);
if (i >= 2) {
System.out.println("remove " + i);
list.remove(i);
// list.remove(0); // line 1
}
}
System.out.println(list);
francisco de feudis wrote:1) why Integer 3 hasn't been removed at the end of the iteration?
francisco de feudis wrote:2) why if I decomment line 1 I get a RuntimeException ? I mean: what is the rule on the basis of we can remove while iterating?
Try to enjoy your work while doing it,it will Automatically convert in Hard Work...
no this is incorrect,try replacing "i" with "0" in your code at line-"list.remove(i)".francisco de feudis wrote:We can remove element that hasn't been indexed by the iterator yet, but not the previous one of the current element?
Try to enjoy your work while doing it,it will Automatically convert in Hard Work...
francisco de feudis wrote:what is the rule on the basis of we can remove while iterating?
Try to enjoy your work while doing it,it will Automatically convert in Hard Work...
francisco de feudis wrote:Indeed list.remove(i) is executed two or more times, because it's placed in the for loop.
Try to enjoy your work while doing it,it will Automatically convert in Hard Work...
francisco de feudis wrote:
Indeed list.remove(i) is executed two or more times, because it's placed in the for loop.
Shouldn't list.remove throw exception even in the first code snippet above, at the second loop?
I think that would be better if java always throw exception when list.remove method is called in for-loops, and let its use instead only outside loops.
What I'm missing?
Java 8 ArrayList JavaDoc wrote:Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.
francisco de feudis wrote:If I can execute
....Shouldn't list.remove throw exception even in the first code snippet above, at the second loop?
Try to enjoy your work while doing it,it will Automatically convert in Hard Work...