Implementing the comparable interface

advertisements

I just found this exam question and cannot figure it out :

The following depicts a contrived partial class which implements the Comparable interface. The only purpose of this contrived class is comparing its instances with a given string.

There are two things we need to fill in in the class to finish it. Here is the class :

public class PrivateComparableClass // FILL IN PART 1 {
   private String thing;

    public PrivateComparableClass(String thing) {
     this.thing=thing;
    }
   //FILL IN PART 2
}

I am assuming part 1 simply corresponds to :

public class PrivateComparableClass implements Comparable {

And part 2, I assume he is expecting an implementation of the compareTo method, but I don't really know how to properly go about implementing this:

public static int compareTo() {
  if this.thing.equals(thing){
  return 1;
  } else {
    return -1;
  }
}

How would I go about fixing this?


First of all, part 1 should really be:

public class PrivateComparableClass implements Comparable<PrivateComparableClass> {

As to part 2, if thing is the only data member in the class, you can simply piggyback on String.compareTo:

public int compareTo(PrivateComparableClass rhs) {
  return this.thing.compareTo(rhs.thing);
}

I recommend that you read up on how compareTo is meant to work (there are three possible outcomes: less than, equal to and greater than).