This week's book giveaway is in the General Computing forum.
We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum 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
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply 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: 2341
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://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: K&B book (mutually comparable)
 
Similar Threads
TreeSet Question
Comparator and Compatable Query
Question about TreeSet and HashSet
How to implement Comparable
Doubt in kathy sierra about hashcode method