0
class GenMethDemo {
    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;
    }

    /*when compiled in java 7 it producing an error and compiling in java 8 without error */
    public static void main(String args[]) {
        Integer nums[] = {1, 2, 3, 4, 5};
        String s[] = {"one", "two", "three"};
        System.out.println(isIn("fs", nums));
      /*
      when compiled in java 7 it producing an error and compiling in java 8 without error */
    }
}
seenukarthi
  • 8,241
  • 10
  • 47
  • 68
  • 3
    Please edit your question to show *text* describing the problem. In particular, what error do you get in Java 7? – Jon Skeet Mar 23 '16 at 15:12
  • `isIn("fs", nums)` shouldn't work since in that case `T` will be `String` and `V` will be `Integer` which does not extend `String`. However Java 8 type inference might be more lenient in that it tries to find a match which would be `T = Object` and `V = Object`. – Thomas Mar 23 '16 at 15:13

2 Answers2

1

This is due to the Generalized Target-type Inference improvements in Java 8. Actually, I answered a question similar to this last week. Java 8 call to generic method is ambiguous

The first answer of the question Java 8: Reference to [method] is ambiguous is also very good.

Java 8 is able infer the type of arguments passed to a generic method. So as @Thomas said in his comment, the type T is inferred to be an Object, and V is inferred to be an object that extends Object, so Integer. In Java 7, this would just throw an error as Integer clearly doesn't extend String.

Community
  • 1
  • 1
AndyN
  • 2,075
  • 16
  • 25
0

In Java 7 type inference would see T = String and V = Integer which won't satisfy V extends T.

However, the JLS for Java 8 states that this would work:

List<Number> ln = Arrays.asList(1, 2.0);

Thus in your case this would be resolved to T = V = Object.

Thomas
  • 87,414
  • 12
  • 119
  • 157