Course contentsShow
← Java
Lesson 1297 of 2,87029. Iterators and IterableFree lesson

Limitations of the Enhanced For Loop

Understanding constraints: no index access, no removal during iteration, forward-only traversal.

Limitations of the Enhanced For Loop

What you'll learn: You'll understand the key constraints that come with using the enhanced for loop and when you need to fall back to explicit iterators or indexed loops.

The Trade-off for Simplicity

While the enhanced for loop makes iteration cleaner and less error-prone, it comes with three significant limitations that you need to know:

1. No Index Access

The enhanced for loop doesn't provide an index variable. If you need to know which position you're at, you're out of luck:

List<String> names = List.of("Alice", "Bob", "Carol");

// Enhanced for: no index available
for (String name : names) {
    // How do I know if this is element 0, 1, or 2?
    System.out.println(name);
}

// Must use traditional loop for index access
for (int i = 0; i < names.size(); i++) {
    System.out.println(i + ": " + names.get(i));
}

2. No Removal During Iteration

You cannot remove elements while using an enhanced for loop. You must use an explicit Iterator with its remove() method:

List<Integer> numbers = new ArrayList<>(List.of(1, 2, 3, 4, 5));

// This will throw ConcurrentModificationException:
// for (Integer num : numbers) {
//     if (num % 2 == 0) numbers.remove(num);
// }

// Must use Iterator instead
Iterator<Integer> it = numbers.iterator();
while (it.hasNext()) {
    if (it.next() % 2 == 0) it.remove();
}

3. Forward-Only Traversal

The enhanced for loop only moves forward. If you need to go backwards or jump around, use a ListIterator or traditional indexed loop.

Key Takeaway: The enhanced for loop is perfect for simple read-only, forward traversal, but requires explicit iterators or indexed loops when you need index access, element removal, or bidirectional navigation.