File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Why Doesn't This Compile? 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 "Why Doesn Watch "Why Doesn New topic

Why Doesn't This Compile?

Kaydell Leavitt
Ranch Hand

Joined: Nov 18, 2006
Posts: 689

The following code doesn't compile. It is from a question at

Looking at the API, I thought that it would have compiled since sort() is defined as follows: ]link

James Boswell

Joined: Nov 09, 2011
Posts: 1051

The API for the sort method you are using states:

All elements in the array
must implement the Comparable interface.
Chris Johansen

Joined: Nov 03, 2011
Posts: 4

I believe the compilation fails because it is unable to determine the order of the elements. It has no rules on how objects of type "Compare" are supposed to be ordered. So for this to compile, you'd need to implement "Comparable" and its mandatory method "compareTo". Happy reading!
Paul Clapham

Joined: Oct 14, 2005
Posts: 19875

It compiles for me. (It throws an exception if you try to run it.) Either the question is wrong, or you misunderstood it.
John Stark
Ranch Hand

Joined: Jul 19, 2011
Posts: 185
Have you done?
Kaydell Leavitt
Ranch Hand

Joined: Nov 18, 2006
Posts: 689

Thanks John, that was it. The following does compile but throws a ClassCastException when it is run. I feel that I understand this code now.

I agree. Here's the link:
subject: Why Doesn't This Compile?
It's not a secret anymore!