1Z0-829 · Question #12
Given the code fragment: class Book { String author; String title; Book(String authorname, String title) { this.author = authorname; this.title = title; } } class SortBook { public static void…
The correct answer is D. At Line n2, replace compareTo() with compare(). Option D as stated appears to be incorrect - this looks like a flawed answer key. Here's the accurate technical breakdown: The real problem is that List.of() (Line n1) creates an immutable list. Calling books.sort() on it throws UnsupportedOperationException at runtime…
Question
Options
- AAt Line n2, replace books.sort() with books.stream().sort().
- BAt Line n1, convert books type to mutable ArrayList type.
- CAt Line n1, convert type to mutable array type.
- DAt Line n2, replace compareTo() with compare().
How the community answered
(56 responses)- A11% (6)
- B5% (3)
- C4% (2)
- D80% (45)
Explanation
Option D as stated appears to be incorrect - this looks like a flawed answer key. Here's the accurate technical breakdown:
The real problem is that List.of() (Line n1) creates an immutable list. Calling books.sort() on it throws UnsupportedOperationException at runtime, regardless of which comparison method is used. The comparison logic a.title.compareTo(b.title) is perfectly valid - String.compareTo() returns an int, satisfying the Comparator<Book> contract exactly as needed.
Option B is actually the correct fix. Changing Line n1 to use a mutable ArrayList (e.g., new ArrayList<>(List.of(...))) allows List.sort() to modify the list in-place.
Why the other distractors fail:
- A is wrong -
Streamhas no.sort()method; you'd need.sorted(), which returns a new stream rather than sorting in place - C is wrong - converting to an array means you'd need
Arrays.sort(), makingbooks.sort(...)a compile error - D is wrong -
Stringhas no staticcompare()method; this replacement wouldn't compile, let alone fix the mutability issue
Memory tip: List.of() = "of" means "off-limits" for mutation. Whenever you see List.of() paired with a mutating operation like sort(), add(), or remove(), the fix is always to wrap it in new ArrayList<>(...).
If this is from an official practice exam, the answer key likely contains an error - flag it for review.
Topics
Community Discussion
No community discussion yet for this question.