I have couple of thoughts regarding the following:
public interface MaxStack>
1-Why does the class tha
In the declaration maxStackclass<T extends Comparable <T>>
you have already expressed the bounds on T
. So you do not need it again.
Reason same as above. No need to specify bounds on the same type parameter again.
<T extends Comparable<T>>
means that T
must implement the Comparable
interface that can compare two T
instances. While <T extends Comparable>
means T
implements Comparable
such that it can compare two Object
s in general. The former is more specific.
if I need to compare bewteen elements in my class, both will be O.K, no?
Well, technically you can achieve the same result using both. But for the declaration <T extends Comparable>
it will involve unnecessary casts which you can avoid using the type safe <T extends Comparable<T>>
1) the class has a type parameter T
with a bound (extends Comparable <T>
), this parameter is passed to the interface (which need the same bound here). When passing a type parameter, you must not repeat its bound - why you should do so?
2) like 1), the type parameter has its bound declared, no repeat neccessary.
To clarify:
The first type parameter occurence (here behind the interface or class name) is its declaration. Any following occurence is a usage. You even never would write a variables type declaration each time you use it, right?
"3-What is the difference between <T extends Comparable<T>>
and <T extends Comparable>
- if I need to compare bewteen elements in my class, both will be O.K, no?"
No, both will not be okay. Suppose I have a class Foo
which implements Comparable<Bar>
but classes Foo and Bar have no relation to each other. Then Foo
cannot compare to other objects of type Foo
. <T extends Comparable<T>>
will catch this as a problem. <T extends Comparable>
will not.