Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

K&B book (mutually comparable)

 
Pawanpreet Singh
Ranch Hand
Posts: 264
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic