please , I want to know the difference between writing
public class Something<T extends Comparable<T>> {// }
and
public class Something<T extends Comparable> {// }
and how would that affect the code
6 Answers. Show activity on this post. Well there's no difference between the first two - they're just using different names for the type parameter ( E or T ). The third isn't a valid declaration - ? is used as a wildcard which is used when providing a type argument, e.g. List<?>
super is a lower bound, and extends is an upper bound.
super E> , it means "something in the super direction" as opposed to something in the extends direction. Example: Object is in the super direction of Number (since it is a super class) and Integer is in the extends direction (since it extends Number ).
The difference is that in the first case the type parameter T
must be comparable to itself whereas in the second case T
can be comparable to anything. Generally, when a class C
is made comparable it is declared to implement Comparable<C>
anyway. Nevertheless, here's an example of when the first wouldn't work but the second would:
class C1<T extends Comparable<T>> { // first case
}
class C2<T extends Comparable> { // second case
}
class A { // some super class
}
class B extends A implements Comparable<A> { // comparable to super class
@Override
public int compareTo(A o) {
return 0;
}
}
Now:
new C1<B>(); // error
new C2<B>(); // works
In general, you should never use the second approach; try to stay away from raw types whenever possible. Also note that an even better option for the second approach would be
public class Something<T extends Comparable<? super T>> { /*...*/ }
Using this with C1
would allow the new C1<B>()
line above to compile as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With