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>
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>
<? 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
.
at first it appears as though the function should return
<E>
but then I seevoid
The <E>
part there is a syntax for supplying generic methods their type argument. The actual return type is void
.
What does this syntax mean
Comparator<? super E>
Comparator<? super E>
This means that the comparator may be for E
or for any of its superclasses.
Comparator<? super E>
? is the wildcard character and the lower bound for this is E.
for example:
private <E> void sort(E[] array, Comparator<? super E> cmp)
if you are passing
qsort(array, 0, array.length - 1, cmp);
if array is Number[] then lower bound of "?" is set to java.lang.Number ie "?" can be anything which is a super class of Number.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.