1

Possible Duplicate:
difference between Iterator and Listiterator?

Recently,while I was goint through javadocs, I found two methods in List interface : iterator() and listIterator(). Apart from different return type, what are the other differences between these two methods? Below is the java doc for both method.

// List Iterators
/**
 * Returns a list iterator over the elements in this list (in proper
 * sequence).
 *
 * @return a list iterator over the elements in this list (in proper
 *         sequence)
 */
ListIterator<E> listIterator();

And

/**
 * Returns an iterator over the elements in this list in proper sequence.
 *
 * @return an iterator over the elements in this list in proper sequence
 */
Iterator<E> iterator();
Community
  • 1
  • 1
Priyank Doshi
  • 12,895
  • 18
  • 59
  • 82

4 Answers4

6

ListIterator is a subclass which extends Iterator.

A ListIterator allows traversal in both directions, rather than just checking if there are more elements (hasNext()), and getting the next one (next()). It maintains a cursor position and calls to next() and previous() will alter the position and return relevant values. ListIterator also allows the addition (add(E e)) of entries, and the setting of entries (set(E e)) to the underlying list (Unlike Iterator, which just allows removing).

Matt Fellows
  • 6,512
  • 4
  • 35
  • 57
4

With ListIterator, you can traverse forward and backward over a list, while you can traverse only forward with Iterator. On the other hand, ListIterator is only used for lists but Iterator is used for map, set, and list.

hcg
  • 642
  • 5
  • 8
1

ListIterator:

A ListIterator has no current element; its cursor position always lies between the element that would be returned by a call to previous() and the element that would be returned by a call to next().

Akhi
  • 2,242
  • 18
  • 24
1

ListIterator is just an extension of plain Iterator, allowing you to traverse the list in either direction, modify the list during iteration, and obtain the iterator's current position in the list.

Joonas Pulakka
  • 36,252
  • 29
  • 106
  • 169