← Back to Chapters

Java Iterator

? Java Iterator

? Quick Overview

Iterator is an interface in Java that allows sequential access to elements of a collection. It is part of the Java Collection Framework and is mainly used to traverse List, Set, and other collections safely.

? Key Concepts

  • Belongs to java.util package
  • Works with all Collection classes
  • Allows forward-only traversal
  • Supports safe removal of elements

? Syntax / Theory

The Iterator interface provides methods to check and retrieve elements one by one.

  • hasNext() – checks if next element exists
  • next() – returns the next element
  • remove() – removes the current element

? Interactive Iterator Simulator

Click the buttons to simulate how an Iterator traverses an ArrayList.

 
System: List created. Iterator ready.

? Code Example

? View Code Example
// Example of using Iterator with ArrayList
import java.util.ArrayList;
import java.util.Iterator;

class IteratorDemo {
public static void main(String[] args) {

ArrayList names = new ArrayList<>();
names.add("Java");
names.add("Python");
names.add("C++");

Iterator it = names.iterator();

while(it.hasNext()) {
String value = it.next();
System.out.println(value);
}
}
}

? Live Output / Explanation

Output

Java
Python
C++

The iterator moves through the collection one element at a time using hasNext() and next().

✅ Tips & Best Practices

  • Use Iterator when you need safe removal during traversal
  • Avoid modifying collection directly while iterating
  • Prefer enhanced for-loop for read-only access

? Try It Yourself

  • Create an ArrayList of integers and iterate using Iterator
  • Remove even numbers using remove()
  • Compare Iterator with for-each loop