简体   繁体   English

如何实现可比性?

[英]How to implement Comparable?

I know how to implement the Comparable interface... I have just one question. 我知道如何实现Comparable接口...我只有一个问题。

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? compareTo方法中,您应该处理obj不是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? 还是应该只假设调用compareTo方法的类仅将其用于其他RealNumber实例?

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. 不,您需要实现Comparable接口的通用形式,以便您可以将RealNumber用作compareTo方法的参数。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM