---
title: "ArrayList Traversals | FiveStudy"
description: "Indexed vs enhanced walks, what each can do, and the skip bug when removal meets the enhanced cursor."
url: https://fivestudy.com/guides/arraylist-traversals
---

[AP Computer Science A](https://fivestudy.com/ap-computer-science-a) · Study guide

# ArrayList Traversals

[Figure: FiveStudy]

FiveStudy

AP® Computer Science A · Data Collections

AP® Computer Science A · Data Collections

# *ArrayList* Traversals

Visiting the elements of an ArrayList with indexed and enhanced for loops, and the special care needed when a traversal removes elements: why forward removal skips elements, two safe techniques, and the exceptions that signal mistakes.

1. Traversing a List 2. Indexed Traversals 3. Enhanced for Traversals 4. Removing Skips Elements 5. Safe Removal 6. Exceptions to Recognize

Big Picture

Traversing an `ArrayList` is when iteration or recursive statements are used to access all or an ordered sequence of its elements. Indexed loops use `get(i)` and `size()`; enhanced `for` loops visit each element directly. Because an `ArrayList` can change size, traversals that delete elements require special techniques to avoid skipping elements, and adding or removing elements in an enhanced `for` loop can cause a `ConcurrentModificationException`. An index outside the valid range causes an `IndexOutOfBoundsException`.

## 1 Traversing a List

Traversing an `ArrayList` is when iteration or recursive statements are used to access all or an ordered sequence of the elements in an `ArrayList`. The same algorithms used with arrays, sums, counts, maximums, searches, work with lists; only the syntax for reaching elements changes, from `a[i]` to `list.get(i)` and from `a.length` to `list.size()`.

The important difference is that a list's size can change during the traversal. Any loop that adds or removes elements must account for that change, or it will skip elements, process some twice, or fail with an exception.

| Traversal | Reads elements | Changes elements (set) | Adds or removes |
| --- | --- | --- | --- |
| Indexed for / while (forward) | Yes | Yes | Only with care: removal skips elements unless handled |
| Indexed for (backward) | Yes | Yes | Removal is safe |
| Enhanced for | Yes | Not by assigning the loop variable | No: ConcurrentModificationException |

## 2 Indexed Traversals

An indexed traversal uses a loop variable as the position: `for (int i = 0; i < list.size(); i++)`, with `list.get(i)` to read each element and `list.set(i, value)` to replace one. Because the condition calls `size()` before every pass, it always reflects the list's current size.

Attempting to access an index value outside of its range will result in an `IndexOutOfBoundsException`. Writing `i <= list.size()` is the usual cause: on the final pass, `get(list.size())` is one past the end.

**Figure 1.** An indexed traversal of an `ArrayList` uses `get(i)` for each index from 0 to `size() - 1`.

Worked Example 1 Indexed traversal

### get and size in a for Loop

Predict the output.

Code

```
ArrayList<String> words = new ArrayList<String>();
words.add("sun");
words.add("sky");
words.add("oak");
words.add("sea");
int letters = 0;
for (int i = 0; i < words.size(); i++)
{
    letters += words.get(i).length();
    System.out.println(i + " " + words.get(i));
}
System.out.println(letters);
```

Output

```
0 sun
1 sky
2 oak
3 sea
12
```

1. 1 **Bounds.** `i` runs from 0 while `i < words.size()`.
2. 2 **`get(i)`** returns each `String`, and `.length()` is called on it.
3. 3 **Total letters:** 4 words × 3 letters = 12.

**Result:** The output lists the four words with their indices and then 12. Traversing an ArrayList with an indexed loop uses `get(i)` and `size()`.

Worked Example 2 Changing elements without resizing

### Using set During a Traversal

Double every value in a list of integers.

Code

```
ArrayList<Integer> nums = new ArrayList<Integer>();
nums.add(3);
nums.add(8);
nums.add(5);
for (int i = 0; i < nums.size(); i++)
{
    nums.set(i, nums.get(i) * 2);
}
System.out.println(nums);
```

Output

```
[6, 16, 10]
```

1. 1 **`set` replaces an element** without changing the size, so an indexed traversal is safe.
2. 2 **Unboxing and autoboxing.** `nums.get(i) * 2` unboxes, multiplies, and `set` autoboxes the result.

**Result:** The output is [6, 16, 10]. Replacing elements with `set` during an indexed traversal works because the list's size stays the same.

Common Mistake 1 · Using <= With size()

`for (int i = 0; i <= list.size(); i++)` makes one pass too many and throws an `IndexOutOfBoundsException` on `get(list.size())`. Use `i < list.size()`.

## 3 Enhanced for Traversals

An enhanced `for` loop visits each element of a list in order: `for (String w : words)`. It is ideal for reading, such as counting, summing, or finding the longest word, and for calling methods on the objects in the list. As with arrays, assigning a new value to the loop variable does not change the list.

Changing the size of an `ArrayList` while traversing it using an enhanced `for` loop can result in a `ConcurrentModificationException`. Therefore, when using an enhanced `for` loop to traverse an `ArrayList`, you should not add or remove elements. Any traversal that resizes the list must use an index.

An enhanced `for` loop can still change the objects in a list, as long as the list itself keeps its size: calling a mutator method on each element changes the objects the list refers to. What it cannot do is replace elements by assigning to the loop variable, or add and remove elements.

**Figure 2.** Changing the size of an `ArrayList` while traversing it with an enhanced `for` loop can result in a `ConcurrentModificationException`.

Worked Example 3 Enhanced for

### Reading Every Element

Find the longest word with an enhanced `for` loop.

Code

```
ArrayList<String> words = new ArrayList<String>();
words.add("lake");
words.add("meadow");
words.add("pine");
String longest = "";
for (String w : words)
{
    if (w.length() > longest.length())
    {
        longest = w;
    }
}
System.out.println(longest);
```

Output

```
meadow
```

1. 1 **Each pass** gives `w` the next element: "lake", "meadow", "pine".
2. 2 **Read-only.** The loop only reads elements and never changes the list's size, which is what enhanced for loops are for.

**Result:** The output is meadow. An enhanced `for` loop is the simplest way to read every element of a list in order.

Worked Example 4 Enhanced for and resizing

### Removing Inside an Enhanced for Loop

What happens?

Code

```
ArrayList<String> words = new ArrayList<String>();
words.add("it");
words.add("is");
words.add("warm");
words.add("ok");
words.add("now");

for (String w : words)
{
    if (w.length() < 4)
    {
        words.remove(0);
    }
}
System.out.println(words);
```

1. 1 **The loop changes the list's size** while the enhanced for loop is still traversing it.
2. 2 **Java detects this** and throws a `ConcurrentModificationException`.
3. 3 **Rule.** When using an enhanced for loop to traverse an ArrayList, do not add or remove elements; use an indexed loop instead.

**Result:** The program stops with a `ConcurrentModificationException`. Changing the size of an ArrayList during an enhanced `for` traversal is not allowed.

Common Mistake 2 · Calling add or remove Inside an Enhanced for Loop

Resizing a list during an enhanced `for` traversal throws a `ConcurrentModificationException`. Switch to an indexed loop whenever elements must be added or removed.

## 4 Why Forward Removal Skips Elements

Deleting elements during a traversal of an `ArrayList` requires the use of special techniques to avoid skipping elements. When `remove(i)` runs, every later element shifts left by one, so the element that was at `i + 1` is now at `i`. A forward loop then increases `i` and moves past that element without ever checking it.

The bug is easy to miss because it only appears when two elements to be removed are next to each other, or when the last element follows a removed one. Tests that include adjacent matches, and matches at the end of the list, reveal it immediately.

Tracing with a table makes the problem visible. Write the list, the value of `i`, and the element being checked on each pass, as in the trace below. The moment a removal happens, the element that slides into index `i` is never written in the "element checked" column, which is exactly the element the loop misses.

**Figure 3.** Deleting elements during a traversal of an `ArrayList` requires special techniques to avoid skipping elements.

| i | List before the check | Element checked | Action |
| --- | --- | --- | --- |
| 0 | [it, is, warm, ok, now] | it | remove → [is, warm, ok, now] |
| 1 | [is, warm, ok, now] | warm | keep (is was skipped) |
| 2 | [is, warm, ok, now] | ok | remove → [is, warm, now] |
| 3 | [is, warm, now] | (3 < 3 is false) | loop ends; now never checked |

Worked Example 5 The skipping bug

### Removing While Moving Forward

The goal is to remove every word shorter than 4 letters. Predict the actual result.

Code

```
ArrayList<String> words = new ArrayList<String>();
words.add("it");
words.add("is");
words.add("warm");
words.add("ok");
words.add("now");

for (int i = 0; i < words.size(); i++)
{
    if (words.get(i).length() < 4)
    {
        words.remove(i);
    }
}
System.out.println(words);
```

Output

```
[is, warm, now]
```

1. 1 **i = 0.** "it" is short and removed; "is" slides into index 0.
2. 2 **i = 1.** The loop checks "warm", skipping "is" entirely (Figure 3).
3. 3 **i = 2.** "ok" is removed; "now" slides into index 2, and then `i` becomes 3, past the end. "now" is never checked.

**Result:** The result is [is, warm, now], not [warm]. Removing during a forward traversal skips the element that slides into the removed position.

## 5 Safe Ways to Remove

The simplest fix is to traverse backward, from `list.size() - 1` down to 0. Removing the element at `i` then shifts only elements with larger indices, which have already been checked, so nothing is skipped.

Another fix keeps the forward direction but increases the index only when no element was removed: after a removal, the same index is checked again, because a new element has slid into it. This is naturally written as a `while` loop. Both techniques check every element exactly once.

A third approach avoids modifying the list being traversed at all: traverse the original and add each element to keep to a new list. Because the traversed list never changes size, even an enhanced `for` loop is safe. This approach also keeps the original data available, which is useful when both the full list and the filtered list are needed later.

**Figure 4.** Traversing backward, or increasing the index only when no element was removed, checks every element exactly once.

Worked Example 6 Removing safely

### Traverse Backward

Fix the removal by traversing from the end.

Code

```
ArrayList<String> words = new ArrayList<String>();
words.add("it");
words.add("is");
words.add("warm");
words.add("ok");
words.add("now");

for (int i = words.size() - 1; i >= 0; i--)
{
    if (words.get(i).length() < 4)
    {
        words.remove(i);
    }
}
System.out.println(words);
```

Output

```
[warm]
```

1. 1 **Start at the last index** and move toward 0.
2. 2 **Why it works.** Removing at index `i` shifts only elements after `i`, which have already been checked.

**Result:** The result is [warm]. Traversing backward is a standard technique for deleting elements from an ArrayList without skipping any.

Worked Example 7 Removing safely

### Advance Only When Nothing Was Removed

A second fix keeps a forward traversal but controls the index carefully.

Code

```
ArrayList<String> words = new ArrayList<String>();
words.add("it");
words.add("is");
words.add("warm");
words.add("ok");
words.add("now");

int i = 0;
while (i < words.size())
{
    if (words.get(i).length() < 4)
    {
        words.remove(i);
    }
    else
    {
        i++;
    }
}
System.out.println(words);
```

Output

```
[warm]
```

1. 1 **After a removal,** `i` stays the same, so the element that slid into position `i` is checked on the next pass.
2. 2 **After keeping an element,** `i` moves on.
3. 3 **The condition** `i < words.size()` uses the current size, which shrinks as words are removed.

**Result:** The result is [warm]. Increasing the index only when no element was removed is another way to delete during a traversal without skipping elements.

Worked Example 8 Another approach

### Collecting the Keepers in a New List

Instead of removing from the original list, copy the words to keep into a new one.

Code

```
ArrayList<String> words = new ArrayList<String>();
words.add("it");
words.add("is");
words.add("warm");
words.add("ok");
words.add("now");

ArrayList<String> kept = new ArrayList<String>();
for (String w : words)
{
    if (w.length() >= 4)
    {
        kept.add(w);
    }
}
System.out.println(kept);
System.out.println(words.size());
```

Output

```
[warm]
5
```

1. 1 **The traversed list never changes size**, so an enhanced for loop is safe here: elements are added to a *different* list.
2. 2 **The original stays intact:** `words` still has 5 elements.
3. 3 **Choose the approach that fits.** Removing changes the original list; collecting leaves it unchanged and produces a separate result.

**Result:** The output is [warm] and 5. Building a new list of the elements to keep avoids the skipping problem entirely and preserves the original data.

Common Mistake 3 · Testing Removal Code Without Adjacent Matches

A forward removal loop works correctly when the elements to remove are never next to each other, so simple tests can pass while the bug remains. Always test with two matching elements in a row and with a match at the end.

## 6 Exceptions to Recognize

Two exceptions signal traversal mistakes. An `IndexOutOfBoundsException` means an index outside 0 to `size() - 1` was used with `get`, `set`, or `remove`, often from a loop bound of `<=` or from an index saved before the list shrank. A `ConcurrentModificationException` means the list was resized during an enhanced `for` traversal.

Silent errors are more dangerous than exceptions: a forward removal that skips elements produces a wrong list without any message. Tracing removal loops with a small, carefully chosen list is the best defense.

| Exception | Cause |
| --- | --- |
| IndexOutOfBoundsException | An index outside 0 to size() − 1 with get, set, or remove |
| ConcurrentModificationException | Adding or removing elements during an enhanced for traversal |

Common Mistake 4 · Remembering an Old Size

Storing `int n = list.size();` before a loop that removes elements and then looping to `n` runs past the end as the list shrinks. Ask the list for its size in the loop condition.

### Four Habits for List Traversals

#### 1. i < list.size()

Ask for the current size every pass.

#### 2. Enhanced for Never Resizes

No add or remove inside it.

#### 3. Remove Backward

Or advance only when nothing was removed.

#### 4. Test Adjacent Matches

They expose skipped elements.

Core Synthesis

Traversing an `ArrayList` is when iteration or recursive statements are used to access all or an ordered sequence of the elements in an `ArrayList`. Deleting elements during a traversal requires special techniques to avoid skipping elements, such as traversing backward or advancing the index only when no element was removed. Attempting to access an index value outside of its range results in an `IndexOutOfBoundsException`. Changing the size of an `ArrayList` while traversing it using an enhanced `for` loop can result in a `ConcurrentModificationException`, so elements should not be added or removed in an enhanced `for` loop.

FiveStudy AP® Computer Science A Study Guide · Data Collections · ArrayList Traversals Back to top ↑
