wood burning stoves 2.0*
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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Why Doesn Watch "Why Doesn New topic
Author

Why Doesn't This Compile?

Kaydell Leavitt
Ranch Hand

Joined: Nov 18, 2006
Posts: 688

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



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

James Boswell
Bartender

Joined: Nov 09, 2011
Posts: 1012
    
    5

The API for the sort method you are using states:

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

Joined: Nov 03, 2011
Posts: 4
Hi!

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
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

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?
John
Kaydell Leavitt
Ranch Hand

Joined: Nov 18, 2006
Posts: 688

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.

 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Why Doesn't This Compile?
 
Similar Threads
Address Book Java Issues
Genric problem
LinkedHashMap - trying to use the method removeEldestEntry
CODE: Dynamic Sorting on Multiple Indexes
BinarySearching an Array sorted in descending order