Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic <T extends Comparable<T>, V extends T> is V required

Tags:

java

generics

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>?

like image 359
Maghesh Avatar asked Dec 05 '25 18:12

Maghesh


1 Answers

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:

  • Any argument that can be passed to the first signature as V[] can be passed to the second signature as T[], since V extends T, so V[] extends T[] (array types in Java are covariant).
  • Any argument that can be passed to the second signature as 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.
like image 120
newacct Avatar answered Dec 08 '25 06:12

newacct



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!