nerdexam
Oracle

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…

Working with Arrays and Collections

Question

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 main(String[] args) { List<Book> books = List.of( new Book("A1", "T1"), new Book("A2", "T2"), new Book("A1", "T2")); // Line n1 books.sort((Book a, Book b) -> a.title.compareTo(b.title)); // Line n2 System.out.println(books); } } Which action sorts the book list?

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)
  • A
    11% (6)
  • B
    5% (3)
  • C
    4% (2)
  • D
    80% (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 - Stream has 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(), making books.sort(...) a compile error
  • D is wrong - String has no static compare() 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

#Collections#Lambda Expressions#Immutable Lists#Comparators

Community Discussion

No community discussion yet for this question.

Full 1Z0-829 Practice