ListIteator Lecture

 

ArrayList <Integer> nums = new ArrayList <Integer> ();

Iterator <Integer> iter = nums.iterator();

iter.add(5);

  i1


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 ...

 

i2  

 

 


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.

 

i3

 


If we use the code:

iter.previous();

iter.previous();

 

and move the iterator between 10 and 15, then we have the following.

 

 

i4

 


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().

 

 

i5

 


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.

 

i6

 

 


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 É

 

i7

 


Remember, you cannot do a set after an add or remove É you must have called next() or previous() immediately prior to calling set.