2

I have a simple generic function

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;
}

and I am callling this funciton with following paramters

Integer nums[] = { 1, 2, 3, 4, 5 };
isIn("abc",nums);

Shouldn't the above code have compile time error as T is upper bound to V. But it compiles without errors

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
arshid dar
  • 1,355
  • 2
  • 15
  • 23
  • http://stackoverflow.com/a/34944269/2775450 – Codebender Jan 23 '16 at 05:31
  • what i am trying to achieve with this function is that if i pass first argument as say integer the array type should also be integer – arshid dar Jan 23 '16 at 06:40
  • 1
    The compiler can infer `T` as a supertype of `Integer` and `String`. For example it would work if `T=Object`. Actually, a more specific type is inferred, something like `Serializable & Comparable extends Serializable & Comparable extends ...> >` (an [infinite type](https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.12.2.7-600) ) – ZhongYu Jan 23 '16 at 07:43

0 Answers0