Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generics excercise - answer explanation [duplicate]

Tags:

java

generics

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.

like image 647
Sebastian Bechtel Avatar asked Mar 06 '26 04:03

Sebastian Bechtel


1 Answers

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>
like image 152
SteeveDroz Avatar answered Mar 08 '26 18:03

SteeveDroz