如何实现Comparable?

时间:2014-12-19 23:21:25

标签: java collections

我知道如何实现Comparable接口......我只有一个问题。

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

compareTo方法中,您是否应该处理obj不是RealNumber实例的情况?在这种情况下你应该抛出异常吗?

或者你应该假设调用compareTo方法的类只对其他RealNumber实例执行此操作?

1 个答案:

答案 0 :(得分:6)

不,您需要实现Comparable interface的通用形式,以便您可以将RealNumber作为compareTo方法的参数。

public class RealNumber implements Comparable<RealNumber> {
    public int compareTo(RealNumber obj) {
        // Don't have to consider when obj isn't a RealNumber.
    }
}