Java Enumeration, Iterator and ListIterator Example


On this page, you will learn about Java cursors. Java provides three cursors i.e. Enumeration, Iterator, and ListIterator to retrieve or fetch the objects or elements one by one from the Collection.

Every cursor in Java has some advantages and disadvantages as well. Check all in the details.

Enumeration

The concept of Enumeration was introduced in 1.0 version. To get the Enumeration object, we can call elements() method of Vector class.

Enumeration<E> e = v.elements();

E – the type of elements returned by this enumeration.

v- any Vector object.

There are only two methods available in Enumeration interface.

public boolean hasMoreElements()– Return true if and only if this enumeration object contains at least one more element to provide; false otherwise.

public Object nextElements()– Returns the next element of this enumeration if this enumeration object has at least one more element to provide and if no more elements exist it will throw NoSuchElementException.

Let’s see the complete example.

EnumerationCursor.java
package org.websparrow.cursor;

import java.util.Enumeration;
import java.util.Vector;

public class EnumerationCursor {

	public static void main(String[] args) {

		Vector<Integer> v = new Vector<>();

		for (int i = 1; i <= 10; i++) {
			v.addElement(i);
		}

		System.out.println("List before operation: " + v);

		Enumeration<Integer> e = v.elements();

		System.out.println("Even number elements of List:");

		while (e.hasMoreElements()) {

			Integer num = e.nextElement();

			if (num % 2 == 0) {
				System.out.println(num);
			}
		}

		System.out.println("List after operation: " + v);
	}
}
Output:
List before operation: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Even number elements of List:
2
4
6
8
10
List after operation: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Limitations of Enumeration

1- Enumeration concept is applicable only for Legacy Classes, hence it is not the universal cursor.

2- We can’t use the Enumeration for ArrayList, LinkedList, etc.

3- By using Enumeration we can only perform the read operation, we can’t perform any remove operation.

Iterator

To overcome the Enumeration, Java introduced Iterator interface in 1.2 version. It is applicable for any Collection implemented classes, hence we can call it universal cursor. Iterator has the capability to remove the objects from the list and method names are improved.

To get the Iterator object, we can call iterator() method of Collection interface.

Iterator<E> itr = c.iterator();

E – the type of elements returned by this iterator.

c- any Collection implemented class.

Iterator interface contains four methods.

public boolean hasNext()– Returns true if the iteration has more elements.

public Object next()– Returns the next element in the iteration and if no more elements exist it will throw NoSuchElementException.

public void remove()– Removes from the underlying collection the last element returned by this iterator. This method can be called only once per call to next().

public void forEachRemaining(Consumer<? super E> action)– It was introduced in 1.8 version. Performs the given action for each remaining element until all elements have been processed or the action throws an exception. Actions are performed in the order of iteration if that order is specified. Exceptions thrown by the action are relayed to the caller.

action – The action to be performed for each element.

Let’s see the complete example.

IteratorCursor.java
package org.websparrow.cursor;

import java.util.Iterator;
import java.util.LinkedList;

public class IteratorCursor {

	public static void main(String[] args) {

		LinkedList<Integer> list = new LinkedList<>();

		for (int i = 1; i <= 10; i++) {
			list.add(i);
		}

		System.out.println("List before operation: " + list);

		Iterator<Integer> itr = list.iterator();

		System.out.println("Even number elements of List:");

		while (itr.hasNext()) {

			Integer num = itr.next();

			if (num % 2 == 0) {
				System.out.println(num);
			} else {
				itr.remove();
			}
		}

		System.out.println("List after operation: " + list);
	}
}
Output:
List before operation: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Even number elements of List:
2
4
6
8
10
List after operation: [2, 4, 6, 8, 10]

Limitations of Iterator

1- An iterator is the forward direction cursor, it can’t move to the previous object.

2- It can perform only read and remove but doesn’t have the capability to replace and add new objects.

ListIterator

ListIterator is the most powerful and bidirectional cursor in Java. It is child interface of Iterator. It was also introduced in 1.2 version. ListIterator has the capability to read, remove, replace, and add the objects over the list.

To get the ListIterator object, we can call listIterator() method of List interface.

ListIterator<E> ltr = list.listIterator();

E – the type of elements returned by this ListIterator.

list- Any List object.

We know that ListIerator is child interface of List, so it will contain all method present in List interface. There are total nine methods available in ListIerator interface.

public boolean hasNext()– Returns true if the iteration has more elements.

public Object next()– Returns the next element in the iteration.

public int nextIndex()– Returns the index of the element that would be returned by a subsequent call to next().

public boolean hasPrevious()– Returns true if this list iterator has more elements when traversing the list in the reverse direction.

public Object previous()– Returns the previous element in the list and moves the cursor position backward.

public int previousIndex()– Returns the index of the element that would be returned by a subsequent call to previous().

public void remove()– Removes from the list the last element that was returned by next() or previous().

public void set(Object obj)– Replaces the last element returned by next() or previous() with the specified element.

public void add(Object obj)– Inserts the specified element into the list.

Let’s see the complete example.

ListIteratorCursor.java
package org.websparrow.cursor;

import java.util.LinkedList;
import java.util.ListIterator;

public class ListIteratorCursor {

	public static void main(String[] args) {

		LinkedList<String> list = new LinkedList<>();

		list.add("Varanasi");
		list.add("Mumbai");
		list.add("New Delhi");
		list.add("Gurgaon");
		list.add("Allahabad");

		System.out.println("List before operation: " + list);

		ListIterator<String> ltr = list.listIterator();

		while (ltr.hasNext()) {

			String cityName = ltr.next();

			if (cityName.equals("Allahabad")) {

				ltr.remove();

			} else if (cityName.equals("Gurgaon")) {

				ltr.set("Gurugram");

			} else if (cityName.equals("Varanasi")) {

				ltr.add("Lucknow");

			} else if (cityName.equals("New Delhi")) {

				System.out.println("Index of New Delhi: " + ltr.nextIndex());
			}
		}

		System.out.println("List after operation: " + list);
	}
}
Output:
List before operation: [Varanasi, Mumbai, New Delhi, Gurgaon, Allahabad]
Index of New Delhi: 4
List after operation: [Varanasi, Lucknow, Mumbai, New Delhi, Gurugram]

Limitations of ListIterator

1- ListIterator is only applicable for List implemented class objects.


About the Author

Atul Rai
I like sharing my experiments and ideas with everyone by writing articles on the latest technological trends.