Enumeration and Iterator Cursors in Collection Framework

Today we will get introduction of Enumeration and Iterator Cursors in Collection Framework. Cursors are used to read Object Data from Collection (ArrayList , Vector). Before you read this article, you must read previous article Introduction to ArrayList with Examples. In java we have three Cursors

  1. Enumeration
  2. Iterator
  3. ListIterator

In this article we will learn about first and second Cursor. We will learn about ListIterator in next article.

Enumeration

Java.util.Enumeration have only two methods hasMoreElement() and nextElement() . hasMoreElement() checks weather the Enumeration contains more element or not. In Simple words, we can say it check weather the Object Data in next Index exist or not. If Enumeration has more element it returns true else false. nextElement() return the next object for the Enmeration.

Let take a simple executable example foe Enumeration

Output:

Enumeration have some limitations.

  1. It is not a universal cursor and It is only applicable for Legacy Classes.
  2. We can only move forward.
  3. Only can retrieve data. Cannot remove, add or replace data.

Iterator

java.util.Iterator is an interface that is introduced in 1.2 version.

Using Iterator we can get next element using next() method. To check if the iteration has more element there is hasNext() method. hasNext() returns true if iteration has next element. We can also remove element using Iterator with remove() method. remove() method removes the object which is returned by the next() method.

Output:

Iterator also have some limitations.

  1. Using Iterator we can only move forward.
  2. We ca only read and remove data. We can’t add or replace data.

To over come these limitations their is third most power full cursor ListIterator that I will explain it in my next article.