1 周,4 日
Questions & Answers
151
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 */
}
}
# 1 楼答案
在Java7中,类型推断将看到
T = String
和V = Integer
,这将不满足V extends T
但是,Java 8的JLS声明这将起作用:
因此,在您的情况下,这将被解析为
T = V = Object
# 2 楼答案
这是由于Java8中对通用目标类型推断的改进。事实上,我上周回答了一个类似的问题Java 8 call to generic method is ambiguous
问题Java 8: Reference to [method] is ambiguous的第一个答案也很好
Java8能够推断传递给泛型方法的参数类型。正如@Thomas在他的评论中所说,类型
T
被推断为Object
,而V
被推断为扩展Object
的对象,因此Integer
。在Java7中,这只会抛出一个错误,因为Integer
显然没有扩展String