I'm confused by this syntax because at first it appears as though the function should return <E>
but then I see void
. What is the purpose of the <E>
prior to the void
?
Also, I'm familiar with bounding and generics, but I've never actually seen something bounded this way. What does this syntax mean Comparator<? super E>
?
Here is a sample function:
private <E> void sort(E[] array, Comparator<? super E> cmp) {
qsort(array, 0, array.length - 1, cmp);
}
The first <E>
is not a type - it is a type constraint.
Bear in mind that Java implements generics via type erasure - this means that the runtime type signature of this method is
private void sort(Object[] array, Comparator cmp)
(by removing everything in between the <>
s) so your method has return type void
.
What <E>
does is to say that the types of the input array and comparator are related: the comparator needs to be able to compare 'things' of type E
, but it actually doesn't have to only handle things of the exact type E
.
This is what <? super E>
does: for example, you could have a Comparator<CharSequence>
, and then use that to sort String[]
, since String
is a subclass of CharSequence
.