Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if object is in array with generic method

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?

like image 619
CBlew Avatar asked Jul 30 '26 21:07

CBlew


1 Answers

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.

like image 140
M. le Rutte Avatar answered Aug 01 '26 11:08

M. le Rutte



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!