how to use comparable

Started by
1 comment, last by haegarr 18 years, 4 months ago
i am required to use comparable on a program and do not fully understand how to use it i assume it compares to objects. can anyone provide some example code as i find it helps me understand
Advertisement
this is in java by the way
In general, you implement the compareTo() function from the Comparable interface, getting an object overhanded, cast the object to the expected class (ok, that may not be needed if you use Java 1.5 / compiler compliance level 5.0), and build a difference. I show a dummy example below:
class Anythingextends Objectimplements Comparable {   public int compareTo(Object other) {      Anything theOther = (Anything)other;      return this.content.getOrdinality() - theOther.content.getOrdinality();   }   public SomethingOrdinal content;}


The example assumes to be able to compute some ordinality from which a difference could be computed. If such isn't possible, you could produce artificially constant return values from the interval [-1,1] but will not yield a total ordering, of course.

(Notice that the interface of Comparable also suggests to overwrite Object.equal for conformance.)

Now you could use it as usual:
Anything a = new Anything();a.content = anInstanceOfSomethingOrdinal;Anything b = new Anything();b.content = anotherInstanceOfSomethingOrdinal;if(a.compareTo(b)<0) {  // do something} else {  // do something other}


P.S.: The public field is here for convenience only and should be supported by setter/getter as usual.

[Edited by - haegarr on December 2, 2005 4:13:21 AM]

This topic is closed to new replies.

Advertisement