Java – Iterator interface with example

In this article, we will discuss Iterator interface in detail.

1. Key points about Iterator:

  • This is introduced in Java 1.2 version
  • Part of Collection framework
  • This is applicable for every collection classes

2. Iterator interface:

  • Iterator interface works on all collection classes
  • This is part of collection framework introduced in Java 1.2 version
  • Iterator interface allows to read objects one-by-one from collection object
  • Also, we can perform remove operation, which is not possible in the legacy Enumeration interface while iterating over collection objects
  • Signature:
public Iterator iterator(); // of Collection interface
  • Present in java.util package

Q) How to get Iterator object ?

  • We can create Iterator object using iterator() method of Collection interface
  • For example,
Iterator itr = col.iterator(); // col is a any collection object

3. Advantages of Iterator over Enumeration:

  • Iterator interface allows to perform both read & remove operations while iterating over collection items
  • This is one of the shortcoming/limitation in legacy Enumeration interface
  • Which Iterator overcomes it

4. Limitation of Iterator interface:

  • It is uni-directional or single-directional cursor
  • But NOT bi-directional cursor
  • That is, Iterator interface is applicable for all collection classes but we can iterate over collection items only in FORWARD direction
  • Iterating over collection items in backward direction is not possible
  • Though both read/remove operations are allowed, but addition of new object is not allowed or
  • replacing old object with new object

5. Iterator interface methods:

 Iterator methodsDescription
boolean hasNext();returns true, if there are more element\objects to be iterated

 

otherwise returns false, if iterator reaches end of Collection

Object next();returns next element/object from Collection

 

throws NoSuchElementException, if there isn’t next element

void remove();removes current element

6. Iterator examples:

IteratorExample.java

package in.bench.resources.java.collection;

import java.util.ArrayList;
import java.util.Iterator;

public class IteratorExample {

	public static void main(String[] args) {

		// creating ArrayList object of type String
		ArrayList<String> al = new ArrayList<String>();

		// adding elements to ArrayList object
		al.add("Sundar Pichai");
		al.add("Satya Nadella");
		al.add("Shiv Nadar");
		al.add("Shantanu Narayen");
		al.add("Francisco D’Souza");

		// creating Iterator reference
		Iterator&amp;lt;String&amp;gt; ceo = al.iterator();

		// enumerating using while loop
		while (ceo.hasNext()){
			System.out.println(ceo.next());
		}
	}
}

Output:

Sundar Pichai
Satya Nadella
Shiv Nadar
Shantanu Narayen
Francisco D’Souza

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java - ListIterator interface
Java - Enumeration interface with example