我知道如何实现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实例起作用?

最佳答案

不,您需要实现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.
    }
}

10-08 05:43