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.
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.
1Traversing 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 |
2Indexed 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.
ArrayList uses get(i) for each index from 0 to size() - 1.get and size in a for Loop
Predict the output.
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);
0 sun
1 sky
2 oak
3 sea
12
- 1Bounds.
iruns from 0 whilei < words.size(). - 2
get(i)returns eachString, and.length()is called on it. - 3Total letters: 4 words × 3 letters = 12.
get(i) and size().Using set During a Traversal
Double every value in a list of integers.
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);
[6, 16, 10]
- 1
setreplaces an element without changing the size, so an indexed traversal is safe. - 2Unboxing and autoboxing.
nums.get(i) * 2unboxes, multiplies, andsetautoboxes the result.
set during an indexed traversal works because the list's size stays the same.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().
3Enhanced 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.
ArrayList while traversing it with an enhanced for loop can result in a ConcurrentModificationException.Reading Every Element
Find the longest word with an enhanced for loop.
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);
meadow
- 1Each pass gives
wthe next element: "lake", "meadow", "pine". - 2Read-only. The loop only reads elements and never changes the list's size, which is what enhanced for loops are for.
for loop is the simplest way to read every element of a list in order.Removing Inside an Enhanced for Loop
What happens?
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);
- 1The loop changes the list's size while the enhanced for loop is still traversing it.
- 2Java detects this and throws a
ConcurrentModificationException. - 3Rule. When using an enhanced for loop to traverse an ArrayList, do not add or remove elements; use an indexed loop instead.
ConcurrentModificationException. Changing the size of an ArrayList during an enhanced for traversal is not allowed.Resizing a list during an enhanced for traversal throws a ConcurrentModificationException. Switch to an indexed loop whenever elements must be added or removed.
4Why 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.
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 |
Removing While Moving Forward
The goal is to remove every word shorter than 4 letters. Predict the actual result.
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);
[is, warm, now]
- 1i = 0. "it" is short and removed; "is" slides into index 0.
- 2i = 1. The loop checks "warm", skipping "is" entirely (Figure 3).
- 3i = 2. "ok" is removed; "now" slides into index 2, and then
ibecomes 3, past the end. "now" is never checked.
5Safe 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.
Traverse Backward
Fix the removal by traversing from the end.
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);
[warm]
- 1Start at the last index and move toward 0.
- 2Why it works. Removing at index
ishifts only elements afteri, which have already been checked.
Advance Only When Nothing Was Removed
A second fix keeps a forward traversal but controls the index carefully.
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);
[warm]
- 1After a removal,
istays the same, so the element that slid into positioniis checked on the next pass. - 2After keeping an element,
imoves on. - 3The condition
i < words.size()uses the current size, which shrinks as words are removed.
Collecting the Keepers in a New List
Instead of removing from the original list, copy the words to keep into a new one.
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());
[warm]
5
- 1The traversed list never changes size, so an enhanced for loop is safe here: elements are added to a different list.
- 2The original stays intact:
wordsstill has 5 elements. - 3Choose the approach that fits. Removing changes the original list; collecting leaves it unchanged and produces a separate result.
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.
6Exceptions 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 |
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.
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.