In Java, the term cursor typically refers to objects used to traverse or iterate over elements in a collection, such as Iterator
, ListIterator
, and Enumeration
. These are called cursor interfaces.
🔹 Types of Cursors in Java
Cursor Type | Introduced In | Applicable Collections | Traversal | Modifications | Direction |
---|---|---|---|---|---|
Enumeration |
JDK 1.0 | Legacy classes (Vector , Hashtable ) |
Read-only | No | Forward |
Iterator |
JDK 1.2 | All Collection types |
Yes | Yes (remove() ) |
Forward |
ListIterator |
JDK 1.2 | Only List types |
Yes | Yes (add() , remove() , set() ) |
Forward and Backward |
🔹 1. Enumeration (Legacy)
import java.util.*;
public class EnumerationExample {
public static void main(String[] args) {
Vector<String> vector = new Vector<>();
vector.add("A");
vector.add("B");
Enumeration<String> enumeration = vector.elements();
while (enumeration.hasMoreElements()) {
System.out.println(enumeration.nextElement());
}
}
}
✅ Read-only and forward-only
🔹 2. Iterator (Modern Standard)
import java.util.*;
public class IteratorExample {
public static void main(String[] args) {
List<String> list = new ArrayList<>(List.of("Apple", "Banana", "Cherry"));
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String fruit = iterator.next();
if (fruit.equals("Banana")) {
iterator.remove(); // Safe removal
} else {
System.out.println(fruit);
}
}
System.out.println("Updated List: " + list);
}
}
✅ Can remove elements during iteration.
❌ Cannot move backward.
🔹 3. ListIterator (Advanced for Lists)
import java.util.*;
public class ListIteratorExample {
public static void main(String[] args) {
List<String> list = new ArrayList<>(List.of("One", "Two", "Three"));
ListIterator<String> listIterator = list.listIterator();
// Forward traversal
while (listIterator.hasNext()) {
String value = listIterator.next();
if (value.equals("Two")) {
listIterator.set("TWO"); // Modify the element
}
}
// Backward traversal
System.out.println("Reverse:");
while (listIterator.hasPrevious()) {
System.out.println(listIterator.previous());
}
System.out.println("Updated List: " + list);
}
}
✅ Supports:
- Forward & backward iteration
- Add, remove, and update
🔹 Cursor Usage Summary
Operation | Enumeration | Iterator | ListIterator |
---|---|---|---|
Forward traversal | ✅ | ✅ | ✅ |
Backward traversal | ❌ | ❌ | ✅ |
Element removal | ❌ | ✅ | ✅ |
Element addition | ❌ | ❌ | ✅ |
Element modification | ❌ | ❌ | ✅ |
Applicable to List | ✅ | ✅ | ✅ |
Applicable to Set | ❌ | ✅ | ❌ |
🔹 Real-World Tip
- Use Iterator when working with general collections like
Set
,Queue
. - Use ListIterator only when working with
List
and you need bidirectional navigation or modification. - Avoid using Enumeration in new code — it's outdated.
Would you like a real-world example like iterating and modifying a custom collection or applying cursors to file or database operations?
Top comments (0)