I was short of time to reply last night, so had to make my reply very brief.
If you make an Iterator a field and instantiate it, it will exist forever and will complain biutterly whenever it notices a “structural alteration” in whichever Collection you are iterating.
You will find more about that in the
documentation. I notice that the
remove() method changed from being an abstract method (see
the Java7 documentation) to a default method. I don't know how much benefit you get from that change; that method has to be overridden in > 90% of cases anyway.
The documentation for
ArrayList#iterator() doesn't tell you a lot, but these two links to its supertype might help more
1 2. If I remember correctly, use of
clear(),
addXXX(),
removeXXX(),
retainAll(), and
sort() alter the List structurally, but (I think)
set() doesn't. The
XXXstream() methods are not allowed to be implemented so as to alter their source Collection. Also you can only call
remove() once per
next() call.
The Iterator keeps a count of the modifications in the List; adding 1 for each call to
remove(). (A
ListIterator has more methods that increment its count.) Similarly the List adds 1 for each alteration. If the Iterator notices a discrepancy between the two counts, it will throw a concurrent modification exception. The conventional way to write an Iterator shown in all the books is like this:-
It should read like this:-
The additional
{...} make the Iterator go out of scope. If you write the following, the Iterator will still be in scope when you call
remove(), which can cause a concurrent modification to be detected and an exception to be thrown.
There aer idfferent ways to make the Iteratro go out of scope: use a plain
for loop:-
Or a
for‑each loop, which treats its underlying Collectiopn in a “read‑” fashion:--
You can of course add and remove things to/rfom Collections without an Iterator; the following plain
for loop works well for something supporting
random access, e.g. an array list, but doesn't work at all well for a linked list:--
I believe that only Lists support a
get() method, because only Lists maintain their elements with an index.
[edit]Two spelling corrections.
[Addition]Don't forget: a
for‑each loop uses an Iterator in the background.