ArrayList<Number> numbers = new ArrayList<Number>();
numbers.add(1);
numbers.add(2.3);
List<Double> doubles = Arrays.asList(1.2, 3.4, 46.7);
copy(numbers, doubles);
public <T> void copy(List<? super T> destination, List<? extends T> source) {
for (T s : source) {
destination.add(s); **// this working fine.**
}
System.out.println(destination);
}
上面的代码有效。但下面的代码不起作用,为什么? 下面我明确告诉编译器 Type 是 Integer 类型。
List<? super Integer> superInteger = Arrays.<Integer>asList(1, 2, 3);
superInteger.add(6); **//this will not give compile time errors but throw unsupportedexception**
最佳答案
它与通配符或 super
关键字无关。 Arrays#asList
方法返回一个固定大小的列表。您无法添加或删除其中。如果您想更改列表,则必须创建一个新列表。
List<? super Integer> superInteger = new ArrayList<Integer>(Arrays.asList(1, 2, 3));
superInteger.add(6); // Now its fine
关于java - super 行为异常的通配符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22578065/