Question discussion

What is the output of the following Java program?import java.util.*; public class Main { public static void main(String[] args) { List l =…

2111Medium DSSSB TGT Computer Science 0 replies

What is the output of the following Java program?

import java.util.*;
public class Main {
    public static void main(String[] args) {
        List<Integer> l = new ArrayList<>(Arrays.asList(1, 2, 3));
        try {
            for (int x : l) {
                if (x == 2) l.remove(Integer.valueOf(x));
            }
        } catch (ConcurrentModificationException e) {
            System.out.print("E");
        }
        System.out.println(l);
    }
}
  • A[1, 2, 3]
  • BE[1, 3]
  • C[1, 3]
  • DE[1, 2, 3]
Correct answer: C

Explanation

Removing the second-last element leaves the iterator's cursor equal to the new size, so hasNext() returns false and no ConcurrentModificationException is thrown; the list is simply [1, 3].

Discussion 0

Nobody has replied yet. Start the discussion!