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
Listand 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)