Java Program to demonstrate the use of Iterator.
Objective
Write a Java program to iterate over a Collection using an Iterator.
Algorithm / Approach
- Create an
ArrayListand populate it with Strings. - Obtain an iterator from the list:
Iterator i = al.iterator();. - Use a
whileloop with the conditioni.hasNext(). - Inside the loop, retrieve the current element using
i.next()and print it.
Test.java
import java.util.*;
class Test {
public static void main(String[] a)
{
ArrayList al = new ArrayList();
al.add("Alok");
al.add("Jeet");
al.add("Anup");
al.add("Ayan");
al.add("Arif");
Iterator i = al.iterator();
while(i.hasNext()) {
System.out.print(i.next()+" ");
}
}
}
Expected Output
Alok Jeet Anup Ayan Arif
Explanation of the Program
- The
Iteratorinterface provides a standardized way to traverse through any Collection in Java, completely hiding the underlying data structure (whether it's an array, a linked list, or a tree). hasNext()checks if there are more elements left in the collection.next()actually retrieves the current element and advances the internal cursor to the next element.
Complexity
Time Complexity
O(n)
Space Complexity
O(1)