Three Cursors in Java Collections

Abhimanyu
1 min readNov 12, 2018

1. Enumeration

  1. Used to retrieve elements one by one from a collection.
  2. Enumerations are also used to specify the input streams to a SequenceInputStream
  3. How to create Enumeration on collections : call elements() method.

Limitations:

  • Not a universal Iterator i.e only applicable to elements of a vector and keys and values of Hashtable.
  • Can not modify collection while iterating through enumeration.
  • Only forward iteration is possible.
EnumerationExample.java

2. Iterator

  1. Iterators in java enable us to retrieve elements one by one.
  2. Iterator support both read and remove operations unlike Enumeration.
  3. Iterators are universal, can be applied to all collections.
  4. Iterator can be created by calling iterator() method on any collection.

Iterators differ from enumerations in two ways:

  • Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
  • Method names have been improved.

Limitations:

  • Single Direction (forward) cursor only.
  • Only read/remove is supported. add/replace is not supported.
IteratorExample.java

3. What is ListIterator?

  1. An iterator for lists that allows the programmer to traverse the list in either direction.
  2. Modify the list during iteration i.e add ,set or replace, remove element.
  3. Obtain the iterator’s current position in the list.
  4. ListIterator Can also be started from a specific index in the list.
  5. ListIterator extends Iterator.

Check all methods:

https://docs.oracle.com/javase/8/docs/api/java/util/ListIterator.html

Limitations:

We can only create listIterator on a List object only(Since listIterator() method is defined in List interface) not on other collections like HashSet, TreeSet etc.

--

--