Topic: Programming in Java
What is printed by modifying an unmodifiable list?
import java.util.*;
public class Test {
public static void main(String []args) {
List<String> base = new ArrayList<>(); base.add("A");
List<String> unmod = Collections.unmodifiableList(base); base.add("B");
System.out.println(unmod.size());
}
}
- A. 1
- B. Throws UnsupportedOperationException on base.add("B")
- C. 2
- D. Compilation Error
Answer: C. 2
Explanation: `Collections.unmodifiableList()` provides a read-only "view" over the original backing list; it does not clone or create a separate copy of the data. Modifying the `unmod` list directly would throw an exception, but modifying the underlying `base` list (`base.add("B")`) is perfectly valid. Since `unmod` is just a view of `base`, it immediately reflects this addition. Therefore, `unmod.size()` evaluates to 2.