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 */
}
}
Asked
Active
Viewed 156 times
0

seenukarthi
- 8,241
- 10
- 47
- 68

shiva reddy
- 11
- 1
-
3Please 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 Answers
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
.