当参数必须为超类类型时,compareTo() 的最佳实践
我正在寻找在类实现 Comparable 的情况下定义compareTo()方法的最佳实践。因此,方法的签名必须是。
public int compareTo(BaseClass arg)
首先要做的显而易见的事情是检查 arg 是否是此类的实例,如果是,则转换为该类,并比较成员。但是,如果参数不是这个类的,而是某个也实现 BaseClass 的其他类,我应该返回什么以使其具有自反性?
我知道,最好的做法是只为它所在的类定义compareTo(),但水已经过了大坝。
I'm looking for best practice for the definition of the compareTo() method in the case where the class implements Comparable. Thus, the signature of the method has to be
public int compareTo(BaseClass arg)
The obvious thing to do first is check if the arg is an instanceof this class, and if so, cast to the class, and compare the members. But if the argument is not of this class, but rather some other class that also implements BaseClass, what do I return so that its reflexive?
I know, the very best practices would be to define compareTo() only for the class it is, but that water is over the dam.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
引自《Effective Java》第 12 条:
您应该执行@BalusC 在他的评论中建议的操作——对所有子类使用基类的compareTo() 方法,或者通过创建一个包含第一个类的实例的不相关的类来执行上面建议的解决方法。
Quote from Effective Java, Item 12:
You should do what @BalusC recommended in his comment -- use the compareTo() method of the base class for all children classes, OR do the workaround suggested above by creating an unrelated class containing an instance of the first class.
你的错误在于你的问题。
您不必实现
public intcompareTo(BaseClass arg)
。您必须实现“public int CompareTo(YourClass arg)”。在这种情况下,您不必使用
instanceof
并执行强制转换。这就是引入泛型的原因:避免强制转换。但是,如果您仍然想使用基类作为参数,请至少执行以下操作:
至少此方法要求参数是基类的子类。
Your mistake is in your question.
You do not have to implement
public int compareTo(BaseClass arg)
. You have to implement 'public int compareTo(YourClass arg)'.In this case you do not have to use
instanceof
and perform cast. This is why generics were introduced: to avoid casting.But if you still want to use base class as an argument do at least the following:
At least this approach requires that the argument is subclass of your base class.
在这种情况下,自反意味着
obj.compareTo(obj) == 0
。这里的反身是什么意思?就compareTo(T o) 的指定约定而言,如果所涉及的类无法进行有意义的比较,则所需的语义是抛出 ClassCastException。
例如,鉴于
有人可能会争辩说
In this context reflexive means
obj.compareTo(obj) == 0
. What do you mean by reflexive here?As far as the specified contract for compareTo(T o), the required semantics are for you to throw a ClassCastException if the classes involved can not meaningfully be compared.
e.g. Given
one could argue that