In “Java the Complete Reference” by Herbert Schildt (10th edition), in chapter 14 on Generics there is the following example of a generic method that checks if an object is in an array:
class GenMethDemo {
static <T extends Comparable<T>, V extends T> boolean isIn(T x, V[] y) {
. . .
}
. . .
}
I don’t understand why V extends T is used here.
Why do we allow array’s type to be the subclass of the object that we check for membership? Shouldn’t it be the other way around?
In this case V needs to be a subclass of T as you want to call Comparable methods on the V[]. If you would allow V to be a super type of T (e.g. an Object[]) you can not call compareTo as these methods are not implemented.
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