1Z0-819 · Question #185
Given: public class Main { public static void main(String[] args) { List<String> list1 = new ArrayList<>(); list1.add("Plane"); list1.add("Automobile"); list1.add("Motorcycle"); List<String> list2 =…
The correct answer is A. A `java.lang.UnsupportedOperationException` is thrown. List.copyOf(list1) returns an unmodifiable list, and calling .sort() on an unmodifiable list triggers UnsupportedOperationException at runtime - this is the key trap. However, there's an important nuance here: the code wraps List.copyOf(list1) in new ArrayList<>(...), which…
Question
Options
- AA
java.lang.UnsupportedOperationExceptionis thrown. - BTrue
- CFalse
- DA
java.lang.NullPointerExceptionis thrown. - EThe compilation fails.
How the community answered
(57 responses)- A82% (47)
- B11% (6)
- C2% (1)
- D4% (2)
- E2% (1)
Explanation
List.copyOf(list1) returns an unmodifiable list, and calling .sort() on an unmodifiable list triggers UnsupportedOperationException at runtime - this is the key trap. However, there's an important nuance here: the code wraps List.copyOf(list1) in new ArrayList<>(...), which actually produces a mutable ArrayList, meaning .sort() on list2 would not throw in practice. This suggests the exam either has a transcription error (the wrapper should be absent: List<String> list2 = List.copyOf(list1);) or an incorrect answer key - with the code exactly as shown, B (true) is what the JVM would actually print, since both lists sort to ["Automobile", "Motorcycle", "Plane"] and ArrayList.equals() compares element-by-element.
Why the distractors are wrong (assuming the intended code lacks the new ArrayList<>() wrapper):
- B (true) and C (false) are both wrong because execution never reaches the
equals()call - the exception halts it first. - D (NullPointerException) is wrong because no null values exist in either list.
- E (compilation fails) is wrong because the code is syntactically valid; the error is purely at runtime.
Memory tip: Think "Copy = Locked." List.copyOf() and List.of() both produce unmodifiable lists - any mutating call (add, remove, sort, set) throws UnsupportedOperationException. Wrapping them in new ArrayList<>(...) is the escape hatch that restores mutability.
Community Discussion
No community discussion yet for this question.