I'm wondering if there's ever a valid use case for the following:
class Base {}
class A implements Comparable<Base> {
//...
}
It seems to be a common pattern (see Collections for a number of examples) to accept a collection of type T
, where T extends Comparable<? super T>
.
But it seems technically impossible to fulfill the contract of compareTo()
when comparing to a base class, because there's no way to ensure that another class doesn't extend the base with a contradictory comparison. Consider the following example:
class Base {
final int foo;
Base(int foo) {
this.foo = foo;
}
}
class A extends Base implements Comparable<Base> {
A(int foo) {
super(foo);
}
public int compareTo(Base that) {
return Integer.compare(this.foo, that.foo); // sort by foo ascending
}
}
class B extends Base implements Comparable<Base> {
B(int foo) {
super(foo);
}
public int compareTo(Base that) {
return -Integer.compare(this.foo, that.foo); // sort by foo descending
}
}
We have two classes extending Base
using comparisons that don't follow a common rule (if there were a common rule, it would almost certainly be implemented in Base
). Yet the following broken sort will compile:
Collections.sort(Arrays.asList(new A(0), new B(1)));
Wouldn't it be safer to only accept T extends Comparable<T>
? Or is there some use case that would validate the wildcard?