Reputation: 3716
Consider these sorting functions in java:
public static <T extends Comparable<? super T>> void sort(T[] a){
}
vs
public static void sort(Comparable[] a){
}
Is there any difference between how you can use these methods? Can for example both the method take an object whose superclass implements a subclass of comparable?
I noticed that for the second method the eclipse editor complains about the function definition with this message: "Comparable is a raw type. References to generic type Comparable should be parameterized."
Upvotes: 2
Views: 124
Reputation: 691755
The first one ensures that all the elements of the array are comparable with each other. The second one only ensures that all the elements implement Comparable.
You may pass an array containing Integer, String and Date instances to the second method, but you can't with the first one. The first one is much type-safer.
Upvotes: 4
Reputation: 71989
The second, as the compiler tells you, doesn't have arguments to the generic type. However, you can just write
public static void sort(Comparable<?>[] a) {
}
which will shut the compiler up.
There isn't actually much difference between the two in terms of usage, except that the former prevents you from passing in an array of broken objects that implement Comparable, where X is not in the superclass chain of the class. (class Y implements Comparable)
In terms of implementation, there is an important difference in that you are limited to sane use of T.
Upvotes: 0