This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan 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 Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "K&B book (mutually comparable)" Watch "K&B book (mutually comparable)" New topic
Author

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: 2367
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: http://aspose.com/file-tools
 
subject: K&B book (mutually comparable)
 
Similar Threads
Comparator and Compatable Query
Question about TreeSet and HashSet
Doubt in kathy sierra about hashcode method
How to implement Comparable
TreeSet Question