ArrayList Traversals
Skill 2.BSkill 3.DSkill 4.A
Big idea: Loop over an ArrayList with get(i) or an enhanced for. Removing while you loop is where bugs hide, because every removal shifts the elements after it.
- Develop code used to traverse the elements of an ArrayList and determine the results of these traversals.
Two ways to loop
CodeArrayList<String> words = new ArrayList<String>();
words.add("sun");
words.add("moon");
words.add("star");
for (int i = 0; i < words.size(); i++) {
System.out.print(words.get(i).length() + " ");
}
System.out.println();
for (String w : words) {
System.out.print(w.substring(0, 1));
}
System.out.println();Output3 4 4 sms
Removing safely
After remove(i), the next element slides into index i. If the loop then does i++, that element is skipped. Two fixes: only increment when you don't remove, or loop backward.
ArrayList<Integer> a = new ArrayList<Integer>(List.of(2, 4, 4, 5));
for (int i = 0; i < a.size(); i++) {
if (a.get(i) % 2 == 0) a.remove(i); // buggy
}
System.out.println(a);
ArrayList<Integer> b = new ArrayList<Integer>(List.of(2, 4, 4, 5));
for (int i = b.size() - 1; i >= 0; i--) {
if (b.get(i) % 2 == 0) b.remove(i); // backward: safe
}
System.out.println(b);Output[4, 5] [5]
Don't change size in an enhanced for
Adding or removing elements inside an enhanced for loop over the same list can throw a ConcurrentModificationException.
ArrayList<String> list = new ArrayList<String>(List.of("a", "b", "c"));
for (String s : list) {
if (s.equals("a")) list.remove(0);
}Outputthrows ConcurrentModificationException- Traverse an ArrayList with indexed loops, enhanced for loops, or recursion.
- Removing during traversal needs care so you don't skip elements.
- An invalid index throws
IndexOutOfBoundsException. - Don't add or remove inside an enhanced for; it can throw
ConcurrentModificationException.
- Forward loop +
remove(i)+i++skips the element that slides into positioni.
List.of(...)appears here only to build sample lists quickly; you won't need it on the exam.
Why does looping backward make removal safe?
Show answer
Removing index i only shifts elements after i, which the loop has already visited.