garg10may garg10may - 5 months ago 9x
Java Question

Generics, V extends T, no error even if incompatible types

I am new to generics. What I understand from below syntax is V should be same or subclass of T, however this shows no compile error and returns False even when V is Integer while T String array.

class GenMethDemo {

public static <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;


public class App {

public static void main(String[] args) {

String b[] = {"are", "how", "YOU"};

System.out.println(GenMethDemo.isIn(1, b));



However if I replace
<T,V extends T>
<T extends Comparable<T>, V extends T>
the behaviour is as expected.


In Java 5/6/7, passing Integer as T and String as V to such generic method would cause "bound mismatch" compiler error unless you explicitly cast first argument to Object.

In Java 8, due to improved type inference, to satisfy relationship between T and V for provided arguments, T is inferred as ? extends Object, which allows V to be String, not resulting an error.

When you restrict to <T extends Comparable<T>, V extends T>, there is no such combination of types T and V which could satisfy Integer and String--even if T falls into the widest possible type Comparable<Integer>, it is not supertype of String. Thus you're getting compiler error as expected.