Skip to main content
← AP CSA Study Guide

Code Scholars Tutoring · AP Computer Science A

6.3: ArrayList Traversal

An indexed loop can replace elements or manage shifting indices. Avoid structural list changes during an enhanced for traversal.

College Board Unit 4

How it works

Traversing an ArrayList uses either an index from 0 while it is less than size(), or an enhanced for loop over the elements. The indexed form is required whenever you need the position or plan to call set. The enhanced form is cleaner for read-only work such as summing, counting, or finding a maximum, but structurally modifying the list while an enhanced for loop is running is unsafe.

Decide before writing the loop whether the list will change during it.

Common error

Caching size() in a variable and then modifying the list, so the bound no longer matches.

Worked example

Java

ArrayList<Integer> list = new ArrayList<Integer>(Arrays.asList(2,4,6));
for (int i = 0; i < list.size(); i++) list.set(i, list.get(i) + 1);
System.out.println(list);

Output

[3, 5, 7]

Each indexed set replaces an element without changing list size.

Exercises

6.3.1 · Trace

Determine the exact output. Explain the Java rule or state changes that produce it.

Java

ArrayList<Integer> list = new ArrayList<Integer>(Arrays.asList(1,2,3));
int sum = 0;
for (int value : list) sum += value;
System.out.println(sum);
Show solution

Output

6

Read-only enhanced traversal visits each element once.

6.3.2 · Write code

Write public static int totalLength(ArrayList<String> words). Assume all elements are non-null. Return the total number of characters, including 0 for an empty list.

Show solution

One valid solution is shown below. Other implementations satisfying the contract are also valid.

Java

public static int totalLength(ArrayList<String> words) {
    int sum = 0;
    for (String word : words) sum += word.length();
    return sum;
}

Check your code

Java

ArrayList<String> a = new ArrayList<String>(Arrays.asList("go","Java",""));
System.out.println(totalLength(a));
System.out.println(totalLength(new ArrayList<String>()));

Expected output

6
0
Practice this topic: MCQ →

Need help with this topic?

Work through questions with a tutor and get help with the steps you find difficult.

Get help with this topic