Jump to content
  • Advertisement
Sign in to follow this  

how to use comparable

This topic is 4860 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post

Link to post
Share on other sites
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 Anything
extends Object
implements 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]

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!