Skip to content

Commit 480e5ac

Browse files
committed
feat(IteratorForEachLoop): add demo comparing for-each, Iterator, and ListIterator
What - Added IteratorForEachLoop class with examples of three traversal techniques: 1. For-each loop: - Iterates list of integers [1,2,3,4,5]. - Prints each element with "For-each element: ". 2. Iterator: - Demonstrates forward traversal with hasNext()/next(). - Creates separate list "numbers" and removes even numbers safely with itr.remove(). - Prints result after removals → [1, 3, 5]. 3. ListIterator: - Demonstrates bidirectional iterator. - Iterates "numbers" with hasNext()/next(). - Shows potential to modify elements with set() or add(). Why - Explains trade-offs between different iteration techniques. - Demonstrates safe removal of elements during iteration (Iterator.remove()). - Shows enhanced functionality of ListIterator for bidirectional traversal and element modification. - Highlights why for-each cannot safely remove elements. How - For-each loop over list: syntactic sugar over Iterator, read-only. - Iterator: - numbers.iterator() returns forward-only cursor. - While loop checks hasNext(), consumes next(). - Even numbers removed safely via itr.remove(). - ListIterator: - numbers.listIterator() allows traversal in both directions. - Iterates forward in demo, prints values. - Could update elements using set(), add(), remove(). Logic - Inputs: - list = [1,2,3,4,5]. - numbers = [1,2,3,4,5]. - Outputs: - For-each prints 1–5. - Iterator prints 1–5, then removes evens, leaving [1,3,5]. - ListIterator prints 1,3,5. - Flow: 1. For-each demonstrates basic traversal. 2. Iterator shows safe removal in traversal. 3. ListIterator highlights richer API (bidirectional, modifications). - Edge cases: - Removing in for-each causes ConcurrentModificationException. - Calling next()/previous() without hasNext()/hasPrevious() throws NoSuchElementException. - Complexity / performance: O(n) for all traversals. - Concurrency / thread-safety: Iterators are fail-fast; not safe with concurrent modification outside iterator. - Error handling: Not needed in demo. Real-life applications - For-each: simple reading (printing, aggregating). - Iterator: filtering/removing unwanted elements during traversal. - ListIterator: implementing editors, undo/redo stacks, or interactive traversals where moving both forward/backward is required. Notes - For-each is concise, but limited. - Iterator is the most common low-level API for traversal + safe removal. - ListIterator is list-specific, with powerful bidirectional operations. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent 2453780 commit 480e5ac

File tree

1 file changed

+105
-0
lines changed

1 file changed

+105
-0
lines changed
Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
import java.util.ArrayList;
2+
import java.util.Iterator;
3+
import java.util.List;
4+
import java.util.ListIterator;
5+
6+
public class IteratorForEachLoop {
7+
public static void main(String[] args) {
8+
// Create an ArrayList of Integers
9+
ArrayList<Integer> list = new ArrayList<>();
10+
list.add(1);
11+
list.add(2);
12+
list.add(3);
13+
list.add(4);
14+
list.add(5);
15+
16+
// 1. Using For-Each Loop
17+
for (int i : list) {
18+
System.out.println("For-each element: " + i);
19+
}
20+
21+
// 2. Using Iterator (Forward Traversal)
22+
System.out.println("Using Iterator:");
23+
Iterator<Integer> iterator = list.iterator();
24+
while (iterator.hasNext()) {
25+
System.out.println(iterator.next());
26+
}
27+
28+
// 3. Removing Elements Using Iterator
29+
List<Integer> numbers = new ArrayList<>();
30+
numbers.add(1);
31+
numbers.add(2);
32+
numbers.add(3);
33+
numbers.add(4);
34+
numbers.add(5);
35+
36+
/*
37+
* NOTE: Removing elements directly inside a for-each loop
38+
* causes ConcurrentModificationException.
39+
* Example (invalid):
40+
*
41+
* for (Integer number : numbers) {
42+
* if (number % 2 == 0) {
43+
* numbers.remove(number); // Not allowed
44+
* }
45+
* }
46+
47+
* Correct way: use Iterator.remove()
48+
*/
49+
System.out.println("Using Iterator to Remove Even Numbers:");
50+
Iterator<Integer> itr = numbers.iterator();
51+
while (itr.hasNext()) {
52+
Integer number = itr.next();
53+
if (number % 2 == 0) {
54+
itr.remove(); // Safe removal
55+
}
56+
}
57+
System.out.println("After removing evens: " + numbers); // [1, 3, 5]
58+
59+
60+
// 4. Using ListIterator (Bidirectional Traversal)
61+
62+
/* ListIterator provides:
63+
* - Forward iteration (hasNext, next)
64+
* - Backward iteration (hasPrevious, previous)
65+
* - Ability to modify elements (set, add, remove)
66+
*/
67+
System.out.println("Using ListIterator:");
68+
69+
ListIterator<Integer> listIterator = numbers.listIterator();
70+
while (listIterator.hasNext()) {
71+
Integer val = listIterator.next();
72+
System.out.println(val);
73+
74+
// Example: You could update elements here
75+
// listIterator.set(val * 10);
76+
}
77+
}
78+
}
79+
80+
/*
81+
1. For-Each Loop
82+
- Simplest way to iterate a collection.
83+
- Read-only iteration (cannot safely remove elements).
84+
85+
2. Iterator
86+
- Provides forward-only traversal of a collection.
87+
- Methods:
88+
hasNext() → check if more elements exist.
89+
next() → fetch next element.
90+
remove() → safely remove the last returned element.
91+
- Important: Use remove() of Iterator, not List.remove(), to avoid ConcurrentModificationException.
92+
93+
3. ListIterator
94+
- An enhanced iterator for Lists.
95+
- Provides bidirectional traversal:
96+
hasPrevious(), previous().
97+
- Supports modification:
98+
set(newValue), add(newElement), remove().
99+
- More powerful than a simple Iterator.
100+
101+
4. Practical Notes
102+
- Use for-each for simple reading.
103+
- Use Iterator when you may need to remove while traversing.
104+
- Use ListIterator when you need bidirectional traversal or in-place updates.
105+
*/

0 commit comments

Comments
 (0)