【发布时间】:2023-03-22 21:01:01
【问题描述】:
我认为我并不真正了解 Java 泛型。这两种方法有什么区别?以及为什么第二个不能编译,错误如下图。
谢谢
static List<Integer> add2 (List<Integer> lst) throws Exception {
List<Integer> res = lst.getClass().newInstance();
for (Integer i : lst) res.add(i + 2);
return res;
}
.
static <T extends List<Integer>> T add2 (T lst) throws Exception {
T res = lst.getClass().newInstance();
for (Integer i : lst) res.add(i + 2);
return res;
}
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - incompatible types
required: T
found: capture#1 of ? extends java.util.List
【问题讨论】:
-
报错信息没有问题;谁说应用程序不能即时编译 java 文件?实际上很多应用程序都可以!错误很明显:方法无法编译;问题很清楚,为什么它不能编译。 @Bruno 没有回答。