Iterators and Enhanced for Loop in Java


Introduction

In Java, Iterators and the Enhanced for Loop are tools for traversing collections. These approaches simplify the process of iterating through data structures such as lists, sets, and arrays.

1. Iterators

An Iterator is an interface in the java.util package that allows us to traverse a collection sequentially. It provides methods to check and retrieve elements.

Common Iterator Methods

  • hasNext(): Checks if there are more elements.
  • next(): Retrieves the next element.
  • remove(): Removes the current element.

Example: Using Iterator

    import java.util.ArrayList;
    import java.util.Iterator;
    
    public class IteratorExample {
        public static void main(String[] args) {
            // Create a list
            ArrayList list = new ArrayList<>();
            list.add("Apple");
            list.add("Banana");
            list.add("Cherry");
    
            // Get an iterator for the list
            Iterator iterator = list.iterator();
    
            // Traverse the list using the iterator
            System.out.println("Iterating using Iterator:");
            while (iterator.hasNext()) {
                String item = iterator.next();
                System.out.println(item);
    
                // Remove "Banana"
                if (item.equals("Banana")) {
                    iterator.remove();
                }
            }
    
            // Display the list after removal
            System.out.println("List after removal: " + list);
        }
    }
        

2. Enhanced for Loop

The Enhanced for Loop, also known as the "for-each" loop, provides a simpler way to iterate over arrays and collections without explicitly using an Iterator.

Example: Using Enhanced for Loop

    import java.util.ArrayList;
    
    public class EnhancedForLoopExample {
        public static void main(String[] args) {
            // Create a list
            ArrayList list = new ArrayList<>();
            list.add("Dog");
            list.add("Cat");
            list.add("Rabbit");
    
            // Traverse the list using the enhanced for loop
            System.out.println("Iterating using Enhanced for Loop:");
            for (String item : list) {
                System.out.println(item);
            }
    
            // The enhanced for loop does not support element removal
        }
    }
        

Differences Between Iterator and Enhanced for Loop

Feature Iterator Enhanced for Loop
Element Removal Supports removal using remove(). Does not support removal.
Complexity Requires explicit use of hasNext() and next(). Simpler and more concise.
Applicability Works with all Collection types. Works with arrays and all Iterable types.

Conclusion

Both Iterators and the Enhanced for Loop are useful for iterating through collections:

  • Iterator: Use when you need to modify or remove elements during iteration.
  • Enhanced for Loop: Use for simple and concise iteration when no modifications are required.




Advertisement