This is from the explanation under the 2nd answer option.It is important to understand that compilation failure occurs because books is declared as List<Book>. If it were declared as just List, compilation would succeed and it would fail at run time with a ClassCastException.
What I understood from the above quote was that the code will compile but will throw a ClassCastException if we have
Code: Select all
List books = getBooksByAuthor("Ludlum");
Collections.sort(books); //2
Basically,
List books = getBooksByAuthor("Ludlum");
is the same as
List<?> books = getBooksByAuthor("Ludlum");
or
List<? extends Object> books = getBooksByAuthor("Ludlum");
Before we can do any sorting, we definitively need to know the type of an object we want to sort but having
List<?> books = getBooksByAuthor("Ludlum");
or
List<? extends Object> books = getBooksByAuthor("Ludlum");
will NOT give us the definitive type of an object we want to sort and thus compiler throws an exception.
In short, the exception occurs even before sorting begins.
Is that correct?
Hypothetically speaking, even if ClassCastException were no issue, the code would still end up not working because to sort an object, the class that the object belongs to would have to implement Comparable Interface or would have to use Comparator Interface somehow to do the sorting.
Am I understanding this correctly?
Thanks.
Schmichael