Reputation: 2725
Can I use <T implements ..>
instead of <T extends...>
?
Can't I use <Comparable>
just without extends/implements?
Why or why not?
class SomeClass
{
public static <T extends Comparable> somemethod(T[] a)
{
// do stuff
}
}
Upvotes: 0
Views: 588
Reputation: 201467
Comparable
is a generic type (and an interface) so you must extend and you cannot implement - it is how Java generics work, also your method is missing a return signature. You could use a Lower Bounded Wildcard like
public static <T extends Comparable<? super T>> T[] somemethod(T... a) {
Arrays.sort(a);
return a;
}
which should work as you expect1. For example,
public static void main(String[] args) {
System.out.println(Arrays.toString(somemethod(4, 3, 1, 2)));
System.out.println(Arrays.toString(somemethod(new Integer[] { 8, 7, 6, 5 })));
}
Outputs
[1, 2, 3, 4]
[5, 6, 7, 8]
1Here, a variadic (varargs) function that sorts but you can use an array if you like.
Upvotes: 4