What is the difference between Iterator and ListIterator

Iterator Interface

Iterator can be used with Set and List types of collections like HashSet, LinkedHashSet, Vector, ArrayList and LinkedList. With iteraor over a collection class, we can iterate in the forward direction using the next and hasNext methods. The following code shows how to use the Iterator interface:

Iterator iterator = osList.iterator();
while(iterator.hasNext()) {
  Map m = (Map) iterator.next();
  Integer osId = Integer.valueOf(m.get("osId").toString());
  if(osId.equals(new Integer(118))) {
	  iterator.remove();
  }
}

In the above code, we are iterating over an ArrayList and removing one of the contained HashMap instance when “osid” with value “118″ is detected.

ListIterator Interface

ListIterator can be used to iterate a collection of type List in both ways forward as well backward. To achieve this, the listIterator provides next, hasNext, previous and hasPrevious methods. Like iterator, listiterator also provides remove method to delete elements from the List type collection. We can use list iterator with ArrayList, Vector and LinkedList etc. Sample code showing the use of List iterator is shown below:

   ListIterator listIterator = osList.listIterator();
 
      
    System.out.println("forward");
    while(listIterator.hasNext()) {
      System.out.println(listIterator.next());
    }
   
    System.out.println("reverse");
    while(listIterator.hasPrevious()) {
      System.out.println(listIterator.previous());
    }

The remove method in iterator and listiterator

Another important difference between Iterator and ListIterator is that while the remove method in iterator interface deletes the last element returned by call to next method, the remove method in ListIterator removes the element returned by last call to next or previous. The remove method in both iterator and listiterator can not be called more than one continuously without invoking return or previous in between those calls to remove().

The pointer in case of iterator stays on the element returned by last call to next method. In case of list iterator, the pointer stays between the elements which shall be returned by calls to next and previous methods. This kind of pointer is required in case of list iterator to remove the elements as described by javadoc of remove method which is reproduced below:

* Removes from the list the last element that was returned by {@link
* #next} or {@link #previous} (optional operation). This call can
* only be made once per call to {@code next} or {@code previous}.
* It can be made only if {@link #add} has not been
* called after the last call to {@code next} or {@code previous}.

Copyright © 2013 Java Experience. All rights reserved.