这是
Comparable接口所面临的确切情况(其
compareTo方法希望采用与调用它的对象相同类型的参数)。那怎么办呢?简称为
Comparable<T>。这个想法是,一个实现类“应该”
Comparable以自身作为参数来实现(允许它与自身“比较”)。但这不是强制性的(因为没有办法这样做)。
是的,正如你指出,这将允许任何类来实现
Comparable与任何其他类的参数:
class Foo implementsComparable<Bar>其中,
Foo和
Bar没有关系对方。但是,这并不是真正的问题。
所有需要
Comparable对象的方法和类(排序,最大值等)都具有以下通用类型约束
<T extends Comparable<? superT>>。这样可以确保类型T的对象与其自身具有可比性。这样,它是完全类型安全的。因此,强制执行不是在Comparable接口的声明中进行的,而是在使用它的地方进行的。
(I notice that you use
<T extends MyInterface<T>>while
Comparableuses
simply
<T>. Although
<T extends MyInterface<T>>will exclude cases where
the type parameter does not implement
MyInterface, it will not exclude cases
where the type parameter does implement
MyInterface, but is different than
the class. So what’s the point of half-excluding some cases? If you adopt
Comparable‘s way of restricting it where they are used, it’s type-safe
anyway, so there is no point in adding more restrictions.)



