This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes K&B book (mutually comparable) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "K&B book (mutually comparable)" Watch "K&B book (mutually comparable)" New topic

K&B book (mutually comparable)

Pawanpreet Singh
Ranch Hand

Joined: Jun 12, 2005
Posts: 264

It is mentioned on page 556(exam watch) in K&B book, about sorting of collection and arrays, the elements should be mutuable comparable.
What does this mean, i have created an object of Car and stored all same object of it into Object[].

In class Car, i have not implemented any Comparable, or not a separate class with Comparator. Hence when i try to
call Array.sort(objects).. it gives ClassCastException.

But when i implement one a Comparable interface, it works fine, does it mean that "if two objects elements are said to be mutually comparable in a collection (TreeSet) or in an array (Object[]), if they implement Comparable interface".

Also same is case of TreeSet (sorted/ordered set)
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2398
Yes, that is the case.

You can understand the reason if you think about the key element in any sort algorithm, the ability to compare elements to see if their positions should be swapped.

When a class definition implements Comparable, objects created from the class definition are Comparable objects.
[ August 01, 2006: Message edited by: Keith Lynn ]
I agree. Here's the link:
subject: K&B book (mutually comparable)
It's not a secret anymore!