Traversing ArrayLists

AP Computer Science A· difficulty 4/5

ArrayList<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
int total = 0;
for (int x : list) {
    total += x;
    if (x == 2) list.add(99);
}
System.out.println(total);

What output is most likely?

  • A

    6

  • B

    99

  • C

    ConcurrentModificationException

    check_circle
  • D

    105

Explanation

Modifying an ArrayList during a for-each loop throws ConcurrentModificationException at runtime.

Want 10 more like this — adaptive to your weak spots?

Related questions