3

In the official Java documentation there are some exercises with answers at the end of the generics chapter. I was able to solve most, however one answer is not clear to me. You can find the questions and answers here. I don't understand the answer on question 8. Why do they write

<T extends Object & Comparable<? super T>>

I did write

<T extends Comparable<? super T>>

and don't see why extends Object is necessary or better.

Sebastian Bechtel
  • 363
  • 1
  • 3
  • 12
  • There is more discussion of this "trick" here: http://www.angelikalanger.com/GenericsFAQ/FAQSections/ProgrammingIdioms.html#FAQ104 – Chris K Oct 22 '16 at 09:46
  • Thanks for your comments, they were very helpful! As I understand it, the Object extension is not necessary and only inserted for not to break the legacy api, which is more or less a bug. So it would be totally fine (or even better) to do it in the way I did... – Sebastian Bechtel Oct 22 '16 at 10:02
  • @user1361466 that is the way that I think of it yes, although it is perhaps less of a bug and more of a feature ;) When adding Generics, the language designers were determined to maintain backwards compatibility with previous releases of Java, and as such (rightly or wrongly) they made many compromises with Generics. – Chris K Oct 22 '16 at 10:06
  • @ChrisK I meant that it was a Bug to define Object as the return Type of max and not Comparable. – Sebastian Bechtel Oct 22 '16 at 10:09

1 Answers1

1

I had to think twice about that one. Here is why:

If you wrote

<T extends Comparable<? super T>>

it would mean that your T has to extend Comparable. What you want is for it to implement Comparable.

In order to do so, you have to make it extend a class and then precise what interfaces must be implemented.

As you don't need any special class, you must then extend Object, once it's done, you can precise what interface to implement.

Syntax:

<T extends ClassToExtend & InterfaceToImplement>
SteeveDroz
  • 6,006
  • 6
  • 33
  • 65
  • If I omit the Object extension then T does not need to be an interface, as I understand it, but a Type. As the comment above suggests, the problem seems to be to be compatible with legacy code which requires the return type to be Object but here we get, after Type erasure, Comparable. – Sebastian Bechtel Oct 22 '16 at 10:00
  • Not quite. For `>`, `T` can be *any* type, interface or class, that is or extends `Comparable`. – Bohemian Oct 22 '16 at 10:09
  • OK, I didn't know a class could extend an interface... Il update my answer. – SteeveDroz Oct 23 '16 at 06:26