1

Why do you think the definition of Comparable<T> lacks an upper bound on T?

That is, why is it not defined as:

Comparable<T extends Comparable<?>>

or

Comparable<T extends Comparable<? super T>>

Wouldn't the latter two proposals be closer to the intended correct use of the interface?

The interface documentation starts with the following sentence, suggesting that it's intended to be used as T implements Comparable<T>:

This interface imposes a total ordering on the objects of each class that implements it.

Is it just for backward compatibility with pre-generic code?

4
  • I don't know how you can say this is opinion based. It has the purely logical answer below Commented Apr 26, 2019 at 12:04
  • An answer that's being debated in the comments on its form, not its merit. And it's unclear from the OP why the proposed definitions would be any better. Commented Apr 26, 2019 at 14:36
  • 1
    T doesn't need qualification for Comparable<T> to work. Your suggestions are limiting what T can be for no obvious reason. T and Comparable<T> are different types. The latter offers a way to compare the former. Comparable<T> places no requirement on T to be anything: T and Comparable<T> do not need to be in a (sub) class relationship Commented Apr 26, 2019 at 18:50
  • "The interface documentation starts with the following sentence, suggesting that it's intended to be used as T implements Comparable<T>" Yes, but there is no way to declare it in Java to guarantee that an implementing class T will implement Comparable<T> In the way you suggested declaring it, interface Comparable<T extends Comparable<? super T>>, you can still declare class Foo implements Comparable<Foo> and then class Bar implements Comparable<Foo>. That would be completely legal according to your declaration. Commented Sep 2, 2019 at 21:43

1 Answer 1

2

Because you can have a type that is comparable to another type.

E.g.

class StringLike implements Comparable<String>
{
    int compareTo(String s) { /* something here */ }
}
3
  • 1
    You can do that, but you are abusing the interface, as proved by the fact that you can't use StringLike with any of the classes/methods that interact with Comparable, like TreeSet or Arrays.sort. Commented Apr 26, 2019 at 12:38
  • You certainly can't use it with anything wanting a String, but you can use it with anything wanting a Comparable<String> Commented Apr 26, 2019 at 12:41
  • 1
    Is there anything in the JDK that works with Comparable<String>? AFAIK everything needs a T that implements Comparable<? super T>. Commented Apr 26, 2019 at 12:51

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.