Implementing a comparable interface

I just found this exam question and cannot understand:

The following is a contrived partial class that implements the Comparable interface. The sole purpose of this contrived class is to compare its instances with a given string.

There are two things we need to fill 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 assume that part 1 just matches:

public class PrivateComparableClass implements Comparable {

And part 2, I assume that he expects the implementation of the compareTo method, but I really don't know how to go about this correctly:

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

How can i fix this?

+3
source share
4 answers

First of all, part 1 should really be:

public class PrivateComparableClass implements Comparable<PrivateComparableClass> {

2, thing , String.compareTo:

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

, compareTo ( : , ).

+5

:

( A B)

  • -1, A <
  • 0, A == B
  • 1, A > B

, compareTo "static", .

+2

-, Comparable ; :

public class PrivateComparableClass 
  implements Comparable<PrivateComparableClass> {

thing compareTo() ( , ).

@Override
public final int compareTo(PrivateComparableClass that) {
  return this.thing.compareTo(that.thing);
}

Comparable equals(), compareTo():

@Override
public final boolean equals(Object obj) {
  if (obj == this)
    return true;
  if (!(obj instanceof PrivateComparableClass))
    return false;
  return compareTo((PrivateComparableClass) obj) == 0;
}

And, when you override equals(), you also need to override hashCode():

@Override
public final int hashCode() {
  return thing.hashCode();
}

If it thingreally is allowed to be null, appropriate method for checking zeros should be added to each method.

+2
source

Well, this is more or less how a class should be declared and implemented.

public class PrivateComparableClass implements Comparable<PrivateComparableClass>
{
    private String thing;
    //... other stuff

    public int compareTo(PrivateComparableClass o)
    {
       return this.thing.compareTo(o.thing);
    }
}
0
source

All Articles