Nearby lessons

87 of 125

Java - Iterators (The Three Cursors)

📌 What You Will Learn
  • What the Collection Framework is and why we need it
  • List, Set, Map and Queue — the four big families
  • Choosing the right collection for the right job
  • Comparable vs Comparator
  • The internal working of HashMap (interview favourite)

Iterators (The Three Cursors) is a core concept of the Java language. This lesson explains The Three Cursors — Enumeration, Iterator, ListIterator with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

The Three Cursors — Enumeration, Iterator, ListIterator

A cursor is a tool that lets you walk through a collection element by element. There are three cursors in Java:

CursorVersionApplicable toOperations
EnumerationJDK 1.0 (legacy)Only legacy classes (Vector, Hashtable)Only read (hasMoreElements, nextElement)
IteratorJDK 1.2All Collection classes (universal)Read + remove
ListIteratorJDK 1.2Only List classesRead + remove + add, and move both forward and backward
Trainer's Note: Fail-fast rule: if you change a collection while iterating with a cursor (other than through the cursor's own methods), you get ConcurrentModificationException. So always remove elements using the cursor's remove(), not the collection's remove().
Example01
JCode Cell
1import java.util.*;
2 
3class Cursors {
4 public static void main(String[] args) {
5 List<String> list = new ArrayList<>(List.of("A", "B", "C"));
6 
7 // Iterator - universal, can remove
8 Iterator<String> it = list.iterator();
9 while (it.hasNext()) {
10 String s = it.next();
11 if (s.equals("B")) it.remove(); // allowed with Iterator
12 }
13 
14 // ListIterator - only for List, moves both ways
15 ListIterator<String> li = list.listIterator(list.size());
16 while (li.hasPrevious()) { // backward direction
17 System.out.print(li.previous() + " ");
18 }
19 System.out.println();
20 
21 // Enumeration - only on legacy Vector/Hashtable
22 Vector<String> v = new Vector<>(List.of("X", "Y"));
23 Enumeration<String> e = v.elements();
24 while (e.hasMoreElements()) {
25 System.out.print(e.nextElement() + " ");
26 }
27 }
28}
Output
C A X Y
📝 Key Takeaways
  • Collection is an interface; Collections is a utility class with static helpers.
  • List = ordered, allows duplicates. Set = no duplicates. Map = key-value pairs. Queue = FIFO.
  • ArrayList is the everyday list; HashMap is the everyday map.
  • HashMap works on hashCode + buckets; collisions chain, then become trees (Java 8+).
  • Comparable (compareTo) is the natural order; Comparator (compare) gives custom order.
  • Always override equals() and hashCode() together for your own objects.
  • Collections.sort() and Collections.reverse() are the handy helpers.

🧠 Test Your Knowledge

1 Questions
Progress: 0 / 1