Skip to content

Commit 2453780

Browse files
committed
feat(IteratorDemo): add demo of traversing list with Iterator
What - Added IteratorDemo class. - Created a List<Integer> with values [5, 10, 50, 60, 70, 80, 90]. - Obtained Iterator<Integer> from list.iterator(). - Used while loop with hasNext() / next() to traverse and print elements. Why - Demonstrates basic usage of Iterator for one-directional traversal of collections. - Shows explicit iteration API instead of enhanced for-loop or streams. - Useful for understanding underlying iteration mechanism and safe element removal. How - list.iterator() returns an Iterator positioned before the first element. - hasNext() checks if more elements exist. - next() advances the iterator and returns current element. - Printed each element sequentially. Logic - Inputs: list of integers. - Outputs: Iterating with Iterator: 5 10 50 60 70 80 90 - Flow: 1. Create list. 2. Get iterator. 3. Traverse while hasNext() true. 4. Print each next(). - Edge cases: - Calling next() without hasNext() throws NoSuchElementException. - Iterator is fail-fast: structural modification of list during iteration throws ConcurrentModificationException (except via iterator.remove()). - Complexity / performance: O(n) traversal. - Concurrency / thread-safety: Iterator not thread-safe; concurrent modification needs synchronized collections or CopyOnWriteArrayList. - Error handling: Not needed in demo. Real-life applications - Iterating over collections when you need explicit control of traversal. - Removing elements safely during iteration via iterator.remove(). - Forms basis for custom traversal algorithms in collections. Notes - Enhanced for-loop (for-each) and streams are syntactic sugar built on top of Iterator. - ListIterator provides bi-directional traversal and element modification, unlike plain Iterator. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent b26b112 commit 2453780

File tree

1 file changed

+17
-0
lines changed
  • Section 25 Collections Frameworks/List Interface/ArrayList/Iterator/src

1 file changed

+17
-0
lines changed
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import java.util.ArrayList;
2+
import java.util.Iterator;
3+
import java.util.List;
4+
5+
/* Demonstrates using Iterator to traverse elements in a single direction. */
6+
7+
public class IteratorDemo {
8+
public static void main(String[] args) {
9+
List<Integer> list = new ArrayList<>(List.of(5, 10, 50, 60, 70, 80, 90));
10+
11+
Iterator<Integer> it = list.iterator();
12+
System.out.println("Iterating with Iterator:");
13+
while (it.hasNext()) {
14+
System.out.println(it.next());
15+
}
16+
}
17+
}

0 commit comments

Comments
 (0)