Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Iterators and Enhanced For Loop in Java

1. Introduction

The Java Collections Framework provides a set of classes and interfaces to handle collections of objects. Iterators and the Enhanced For Loop are two essential features for traversing collections in Java.

2. Iterators

An Iterator is an interface in Java that provides methods to iterate over a collection. It allows the caller to remove elements from the underlying collection during the iteration.

Key Methods of Iterator

  • hasNext(): Returns true if there are more elements to iterate.
  • next(): Returns the next element in the iteration.
  • remove(): Removes the last element returned by the iterator.

Example of Using an Iterator

import java.util.ArrayList;
import java.util.Iterator;

public class IteratorExample {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("Apple");
        list.add("Banana");
        list.add("Cherry");

        Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()) {
            String fruit = iterator.next();
            System.out.println(fruit);
            if (fruit.equals("Banana")) {
                iterator.remove(); // Removing Banana
            }
        }
        System.out.println(list); // Output: [Apple, Cherry]
    }
}

3. Enhanced For Loop

The Enhanced For Loop (or for-each loop) provides a simpler way to iterate over collections and arrays without the need for an explicit iterator.

Syntax

for (ElementType element : collection) {
    // Process element
}

Example of Using Enhanced For Loop

import java.util.ArrayList;

public class EnhancedForLoopExample {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("Apple");
        list.add("Banana");
        list.add("Cherry");

        for (String fruit : list) {
            System.out.println(fruit);
        }
    }
}

4. Best Practices

Note: Use Iterators when you need to safely remove elements during iteration.
  • Use the Enhanced For Loop for read-only access to collections.
  • Prefer using Collections and Arrays as they provide built-in iterators and enhanced for loop capabilities.
  • Always check for concurrent modifications when using Iterators.

5. FAQ

Can I modify a collection while using the Enhanced For Loop?

No, modifying a collection directly while using the Enhanced For Loop will throw a ConcurrentModificationException.

What is the difference between Iterator and ListIterator?

ListIterator can traverse the list in both directions (forward and backward) and can also modify the list during iteration.