why*_*why 15 java generics nested-generics java-6
在以下示例中:
public static void main(String[] args) {
List<String> b = new ArrayList<String>();
first(b);
second(b);
List<List<String>> a = new ArrayList<List<String>>();
third(a);
fourth(a); // doesnt work
}
private static <T> void first(List<T> a){
System.out.println("List of T");
}
private static void second(List<?> a){
System.out.println("List of anything ");
}
private static <T> void third(List<List<T>> a){
System.out.println("List of a List of T ");
}
private static void fourth(List<List<?>> a){
System.out.println("List of a List of anything ");
}
Run Code Online (Sandbox Code Playgroud)
为什么第二个(b)的呼叫有效,但第四个(a)的呼叫不起作用?
我收到以下错误:
The method fourth(List<List<?>>) in the type `TestTest` is not applicable for the arguments (`List<List<String>>`)
Run Code Online (Sandbox Code Playgroud)
Luk*_*der 14
如果您希望能够fourth
使用List<List<String>>
参数调用,那么您需要将签名更改为:
private static void fourth(List<? extends List<?>> a){
System.out.println("List of a List of anything ");
}
Run Code Online (Sandbox Code Playgroud)
以上将有效,因为不兼容List<List<?>>
,List<? extends List<?>>
兼容List<List<String>>
.想一想:
List<List<String>> original = null;
List<? extends List<?>> ok = original; // This works
List<?> ok2 = original; // So does this
List<List<?>> notOk = original; // This doesn't
List<Integer> original = null;
List<? extends Number> ok = original; // This works
List<?> ok2 = original; // So does this
List<Number> notOk = original; // This doesn't
Run Code Online (Sandbox Code Playgroud)
推理很简单.如果你有
private static void fourth(List<List<?>> a) {
List<?> ohOh = Arrays.asList(new Object());
a.add(ohOh);
}
Run Code Online (Sandbox Code Playgroud)
然后,如果您可以这样调用该方法:
List<List<String>> a = new ArrayList<List<String>>();
fourth(a);
String fail = a.get(0).get(0); // ClassCastException here!
Run Code Online (Sandbox Code Playgroud)
A List<List<String>>
不是List<List<?>>
.
无论如何,你应该能够把任何东西都List<?>
放进List<List<?>>
去?
.A List<List<String>>
只会接受一个List<String>
.
归档时间: |
|
查看次数: |
1289 次 |
最近记录: |