1

I know how to implement the Comparable interface... I have just one question.

public class RealNumber implements Comparable {
    public int compareTo(Object obj) {
        // What do you do when obj is not an instance of RealNumber?
    }
}

In the compareTo method, are you supposed to handle the case where obj is not an instance of RealNumber? Should you throw an Exception in this case?

Or should you just assume the class invoking your compareTo method only does it for other RealNumber instances?

ktm5124
  • 11,861
  • 21
  • 74
  • 119

1 Answers1

6

No, you need to implement the generic form of the Comparable interface, so that you can take a RealNumber as a argument to the compareTo method.

public class RealNumber implements Comparable<RealNumber> {
    public int compareTo(RealNumber obj) {
        // Don't have to consider when obj isn't a RealNumber.
    }
}
rgettman
  • 176,041
  • 30
  • 275
  • 357