Reputation: 11
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 */
}
}
Upvotes: 0
Views: 159
Reputation: 88707
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
.
Upvotes: 0
Reputation: 2105
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
.
Upvotes: 1