Page 1 of 1

About Questions 1830 and 1875

Posted: Fri Dec 16, 2016 8:46 pm
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!

Re: About Questions 1830 and 1875

Posted: Fri Dec 16, 2016 10:59 pm
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.