The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes SCJP Book's Quiz B Question 54 - Comparable Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "SCJP Book Watch "SCJP Book New topic

SCJP Book's Quiz B Question 54 - Comparable

Katherine Reut

Joined: Jul 26, 2013
Posts: 28
I'm going through the quizzes on the CD that came with the SCJP6 book. I don't understand one of the explanations for Quiz B Question 54. The question is:

Which are true (Choose all that apply.)

A. You can use java.lang.Comparable and java.util.Comparator to sort collections whose elements are of any valid Java type as long as all of the collections elements are of the same class.
B. The java.lang.Object class implements the java.lang.Comparable interface.
C. Many commonly used classes in the Java AP (such as String, Integer, Date, and so on) implement the java.lang.Comparable interface.
D. If your class implements java.lang.Comparable but you don't explicitly override Comparable's method, collections containing elements of your class will be sorted in natural order by default.
E. When using the java.util.Comparator interface, you will typically create a separate class for every different sort sequence you want to implement.
F. The java.util.Comparator's interface's method can take either one or two arguments.
G. The binarySearch(), reverse(), and reverseOrder() methods in the java.util.Collections class all require that the collection is sorted before the method can be invoked successfully.

The answer states:
"A is incorrect because if a class is final and does not already implement Comparable, then Comparable can't be used to sort that class."

I don't understand. How would one use java.lang.Comparable other than having the class in question implement Comparable? What I mean is, I interpreted "A"'s statement "You can use java.lang.Comparable..." to mean that the class in question was implementing java.lang.Comparable. I think that I am missing something about a different way to use Comparable other than implementing it in the class definition.

Can one of the Ranchers here help me out with an example of how Comparable could be used unsuccessfully to sort a collections of elements that are of the same class? Thanks in advance everyone!
Katherine Reut

Joined: Jul 26, 2013
Posts: 28
Update: I tried out the below code as an experiment to see if I could do as "A" stated (i.e. make a class final and have it not implement Comparable, and then as a result not be able to use comparable to sort the class. The code works, so I'm doing something wrong. Does anyone have any ideas about how to demonstrate answer "A" with real code?

The result is:

I agree. Here's the link:
subject: SCJP Book's Quiz B Question 54 - Comparable
It's not a secret anymore!