JavaAdvanced#puzzle#collections

What is the output? List<Integer> list = new ArrayList<>(); list.add(1); list.add(2); for (Integer i : list) { if (i == 1) list.remove(i); }

Modifying a List while iterating with a for-each loop (which uses an Iterator internally) throws ConcurrentModificationException, since ArrayList's iterator is fail-fast and detects the structural modification.

Example
List<Integer> list = new ArrayList<>(List.of(1, 2));
for (Integer i : list) {
  if (i == 1) list.remove(i); // throws ConcurrentModificationException
}

Related Questions

1
JavaIntermediate#puzzle#oop

What is the output of this code involving static and instance initialization order? class A { static { System.out.println("static A"); } { System.out.println("instance A"); } A() { System.out.println("constructor A"); } } new A(); new A();

Open
2
JavaIntermediate#puzzle#fundamentals

What does this print? Integer a = 127; Integer b = 127; Integer c = 128; Integer d = 128; System.out.println(a == b); System.out.println(c == d);

Open
3
JavaBeginner#puzzle#operators

What is the output? public class Test { public static void main(String[] args) { System.out.println(10 / 3); System.out.println(10.0 / 3); System.out.println(10 % 3); } }

Open