gpt4 book ai didi

java - 如果参数是同一接口(interface)的不同实现,compareTo() 应该返回什么?

转载 作者:行者123 更新时间:2023-12-01 07:46:39 25 4
gpt4 key购买 nike

有接口(interface)

interface Animal extends Comparable<Animal> {
}

和 2 类

class Dog implements Animal {

}

class Cat implements Animal {

}

当争论与 Animal 的具体实现不同时,compareTo(Animal o) 应该返回什么?

它应该抛出IllegalArgumentException吗?

例如,如果我将 Dog 实例传递给 Cat.compareTo()。我无法比较它们,因为它们是不同的类型。我无法引用 super.compareTo() 因为它们的 super 是 Object 类型,它没有实现 Comparable 。将 Dog 转换为 Cat 将抛出 ClassCastException

最佳答案

interface Animal不应该实现Comparable<Animal>首先,如果您不希望其子类相互比较。

Effective Java 2nd Ed 的第 8 条“考虑实现 Comparable”中有一段相关引用(我从 my answer to this question 复制了以下大部分内容):

One consequence of these three provisions [of the compareTo contract] is that the equality test imposed by a compareTo method must obey the same restrictions imposed by the equals contract: reflexivity, symmetry, and transitivity. Therefore the same caveat applies: there is no way to extend an instantiable class with a new value component while preserving the compareTo contract, unless you are willing to forgo the benefits of object-oriented abstraction (Item 8).

所以,这意味着假设您的子类没有比用于确定排序的父类(super class)更多的值,实现 Comparable<Supertype>是合理的。

这其中的含义,除了 Comparable 的一般要求之外,是Comparable<Superclass>应该在 Superclass 中同样实现以及所有子类。

关于java - 如果参数是同一接口(interface)的不同实现,compareTo() 应该返回什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50410668/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com