• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to implement Comparable  RSS feed

Niranjan Deshpande
Ranch Hand
Posts: 1277
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
//What changes need to be done if i want to
// implement Comparable.The compiler tells to override "compareTo()"
//method. But what should be its body so that i get the same output
//as obtained by implementing Comparator

import java.util.*;
public class Car implements Comparator {
public int wheels = 0;
public Car(){}
public Car(int wheels) {
this.wheels = wheels;
public int compare(Object o1, Object o2) {
Car c1 = (Car)o1;
Car c2 = (Car)o2;
return new Integer(c1.wheels).compareTo(new Integer(c2.wheels));
//if you interchage c1 and c2, you
// will get o/p in descending order
public String toString() {
return new Integer(wheels).toString();
public static void main(String[] args) {
Car c1 = new Car(1);
Car c2 = new Car(2);
Car c3 = new Car(3);
TreeSet list = new TreeSet(new Car());
Iterator it = list.iterator();
while (it.hasNext())
System.out.print (it.next() + " ");

Compilation succeeds, the output is 1 2 3
The compilation succeeds and the output will be in ascending order
(e.g.: 1 2 3).
The class Car is a Comparator but at the same time also a
business object that contains the total of wheels for the car.
At line 25 the TreeSet is created, the TreeSet of the constructor
takes in
the Car() Comparator, this constructor creates a new empty set
sorted according to the Car criteria(see Car.txt).
All elements must be mutually comparable by the
car.compare(Object o1, Object o2) method. The Car object used to
create the
TreeSet does not belong to the set.

The cars are sorted by the total amount of wheels.
3 new objects are created and added to a list.
When the TreeSet start sorting it will call
the compare method and it compares the
total of wheels. It uses the Integer compareTo method.
Seb Mathe
Ranch Hand
Posts: 225
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
With Comparable, instead of comparing 2 objects (as compare in Comparator do), you'll compare "this" object with another one.

So your job for moving from Compartor to Comparable should be easy...
Steve Morrow
Ranch Hand
Posts: 657
Clojure Spring VI Editor
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!