[英]Generic Type Mismatch
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 */
}
}
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对Generalized Target-Type Inference的改进所致。实际上,我回答了与上周类似的问题。 Java 8 call to generic method is ambiguous Java 8对泛型方法的调用不明确
The first answer of the question Java 8: Reference to [method] is ambiguous is also very good. Java 8:对[方法]的含糊不清的问题的第一个答案也很好。
Java 8 is able infer the type of arguments passed to a generic method. Java 8能够推断传递给泛型方法的参数类型。 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
. 因此,正如@Thomas在他的评论中所说,类型T
推断为Object
,而V
推断为扩展Object
,即Integer
。 In Java 7, this would just throw an error as Integer
clearly doesn't extend String
. 在Java 7中,这只会引发错误,因为Integer
显然不会扩展String
。
In Java 7 type inference would see T = String
and V = Integer
which won't satisfy V extends T
. 在Java 7中,类型推断将看到T = String
和V = Integer
,这将不满足V extends T
However, the JLS for Java 8 states that this would work: 但是,用于Java 8的JLS声明可以正常工作:
List<Number> ln = Arrays.asList(1, 2.0);
Thus in your case this would be resolved to T = V = Object
. 因此,在您的情况下,这将解析为T = V = Object
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.