About Questions 1830 and 1875

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
ibugaienko
Posts: 6
Joined: Wed Dec 14, 2016 11:29 pm
Contact:

About Questions 1830 and 1875

Post by ibugaienko »

Hi All,

I'm struggling to understand how these two snippets of code are different and why one fails to compile while the other one throws and exception at RT. Could somebody explain please?

#1

Code: Select all

List<Book> books = getBooksByAuthor("Ludlum");
Collections.sort(books, (b1, b2)->b1.getTitle().compareTo(b2.getTitle()));//1
Collections.sort(books); //2
#2

Code: Select all

List<Book> books = getBooksByAuthor("Ludlum"); books.stream().sorted().forEach(b->System.out.println(b.getIsbn())); //1
Thanks!

admin
Site Admin
Posts: 10388
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: About Questions 1830 and 1875

Post by admin »

This is already explained in the option of 1830:
Collections.sort method takes a List parameter with elements that must be of type Comparable. See the signature of Collections.sort:

Code: Select all

public static <T extends Comparable<? super T>> void sort(List<T> list)
Book does not implement Comparable so List<Book> does not satisfy the above signature. The compiler can see that and it fails to compile the code.

The code in 1875, uses the Stream.sorted() method, which takes no parameters. The sorted method casts the elements to Comparable at run time. So the compiler has nothing to check here.

HTH,
Paul.

Post Reply

Who is online

Users browsing this forum: No registered users and 29 guests