I am attaching an example, which shows how to use Comparable interface. In this example, I am comparing Rabbits based on their ear length. Let me know if you have any questions over this example:
/**
* @author Srinivas Velamuri
*
*/
public class ComparableExample {
public static void main(
String[] args) {
Rabbit myRabbit = new Rabbit(7); // my Rabbit with 7 inches ears
Rabbit[] rabbits = new Rabbit[10];
for (int i=0; i < rabbits.length; i++) {
rabbits[i] = new Rabbit(i+2);
if ( myRabbit.compareTo(rabbits[i]) > 0) {
System.out.println ("myRabbit is bigger than the rabbit at position " + i + " in the Rabbit collection");
} else if ( myRabbit.compareTo(rabbits[i]) < 0) {
System.out.println ("myRabbit is smaller than the rabbit at position " + i + " in the Rabbit collection");
} else {
System.out.println ("myRabbit is same than the rabbit at position " + i + " in the Rabbit collection");
}
}
}
}
class Rabbit implements Comparable {
private int earLength; // in inches
Rabbit(int earLength){ // constructor
this.earLength = earLength;
}
public int compareTo(Object anotherRabbit) {
if (this.earLength > ((Rabbit)anotherRabbit).getEarLength()) {
return 1;
} else if (this.earLength < ((Rabbit)anotherRabbit).getEarLength()) {
return -1;
} else {
return 0;
}
}
public int getEarLength() {
return earLength;
}
}