0
0
JavaHow-ToBeginner · 3 min read

How to Iterate ArrayList in Java: Simple Syntax and Examples

To iterate an ArrayList in Java, you can use a simple for loop with index, an enhanced for-each loop, or an Iterator. Each method lets you access elements one by one to perform actions or read values.
📐

Syntax

Here are common ways to iterate an ArrayList in Java:

  • For loop with index: Use a counter to access elements by position.
  • Enhanced for-each loop: Automatically loops through each element.
  • Iterator: Use an Iterator object to traverse the list safely.
java
ArrayList<Type> list = new ArrayList<>();

// For loop with index
for (int i = 0; i < list.size(); i++) {
    Type element = list.get(i);
    // use element
}

// Enhanced for-each loop
for (Type element : list) {
    // use element
}

// Iterator
Iterator<Type> iterator = list.iterator();
while (iterator.hasNext()) {
    Type element = iterator.next();
    // use element
}
💻

Example

This example shows how to create an ArrayList of strings and iterate it using all three methods to print each element.

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

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

        System.out.println("Using for loop with index:");
        for (int i = 0; i < fruits.size(); i++) {
            System.out.println(fruits.get(i));
        }

        System.out.println("\nUsing enhanced for-each loop:");
        for (String fruit : fruits) {
            System.out.println(fruit);
        }

        System.out.println("\nUsing Iterator:");
        Iterator<String> iterator = fruits.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}
Output
Using for loop with index: Apple Banana Cherry Using enhanced for-each loop: Apple Banana Cherry Using Iterator: Apple Banana Cherry
⚠️

Common Pitfalls

Common mistakes when iterating an ArrayList include:

  • Using a for loop but calling list.get(i) with an index out of bounds.
  • Modifying the list (adding/removing elements) while iterating without using an Iterator, which causes ConcurrentModificationException.
  • Forgetting to check iterator.hasNext() before calling iterator.next().
java
import java.util.ArrayList;
import java.util.Iterator;

public class PitfallExample {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("A");
        list.add("B");
        list.add("C");

        // Wrong: modifying list during for-each loop causes error
        // for (String s : list) {
        //     if (s.equals("B")) {
        //         list.remove(s); // Causes ConcurrentModificationException
        //     }
        // }

        // Right: use Iterator to remove safely
        Iterator<String> it = list.iterator();
        while (it.hasNext()) {
            String s = it.next();
            if (s.equals("B")) {
                it.remove();
            }
        }

        System.out.println(list); // Output: [A, C]
    }
}
Output
[A, C]
📊

Quick Reference

Summary of iteration methods for ArrayList:

MethodDescriptionWhen to Use
For loop with indexAccess elements by position using indexWhen you need the index or want to modify elements by position
Enhanced for-each loopSimpler syntax to access each elementWhen you only need to read elements
IteratorTraverse and safely remove elements during iterationWhen you need to remove elements while looping

Key Takeaways

Use a for loop, enhanced for-each loop, or Iterator to iterate an ArrayList in Java.
Avoid modifying the list during a for-each loop; use Iterator's remove method instead.
Enhanced for-each loop is the simplest way to read elements without needing the index.
Always check iterator.hasNext() before calling iterator.next() to avoid errors.