Commit 2453780
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 changedLines changed: 17 additions & 0 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
0 commit comments