ListIteator Lecture
ArrayList
<Integer> nums = new ArrayList <Integer> ();
Iterator
<Integer> iter = nums.iterator();
iter.add(5);
If nums is empty but has a ListIterator,
then adding 5 places the iterator to the right of the newly added value.
If the list has these values
...
with the iterator after the
last item and we add a new value 20, then the iterator will be at the end of
the list after 20.
If we use the code:
iter.previous();
iter.previous();
and move the iterator between
10 and 15, then we have the following.
If we now wish to add 12,
then 12 will be added between 10 and 15 and the iterator will end up being to
the right of 12 once the insertion is complete. We can add because we called iter.previous() before calling
add. We could also have added if
we had used iter.next().
Remember, you cannot do an
add followed by a remove. That
causes an IllegalStateException.
(Who would want to add something and then immediately remove it anyway?)
DonÕt forget É remove deletes
the last value that was returned by a call to next() or previous(). It all depends on which direction the
iterator is moving.
If we now use the code É
iter.next();
iter.next();
then our iterator has now
moved to the following position.

If we then call the set()
method, we will be replacing 20 with a new value É.
iter.set(18);
and our list now looks like
this É
Remember, you cannot do a set
after an add or remove É you must have called next() or previous() immediately
prior to calling set.