我不认为我真的了解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;
}
Run Code Online (Sandbox Code Playgroud)
.
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
Run Code Online (Sandbox Code Playgroud)