Came across this example in Java Complete Reference under Generics method.
static <T extends Comparable<T>, V extends T> boolean isIn(T x, V[] y) {
for(int i=0; i < y.length; i++)
if(x.equals(y[i])) return true;
return false;
}
Here V extends T is confusing. Can we only have <T extends Comparable<T>> to get the job done. Because T extends some type which means the type and its sub type. Then why we need V extends T?. Is there any special case for using <T extends Comparable<T>, V extends T>?
Yes, in this case, since the V is only used in one place, in the type of a parameter as V[], and since array types are covariant, the V is unnecessary and the method can be written with this signature:
static <T extends Comparable<T>> boolean isIn(T x, T[] y)
The two method signatures would accept the same sets of arguments (assuming the caller does not specify an explicit type signature. You can see this as follows:
V[] can be passed to the second signature as T[], since V extends T, so V[] extends T[] (array types in Java are covariant).T[] can be passed to the first signature as V[], because the compiler can always infer V as T, since T is within V's bounds. Such an inference will not cause problems anywhere else since V is not used anywhere else.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