WildcardError.java:6: error: method set in interface List<E> cannot be applied to given types;
i.set(0, i.get(0));
^
required: int,CAP#1
found: int,Object
reason: actual argument Object cannot be converted to CAP#1 by method invocation conversion
where E is a type-variable:
E extends Object declared in interface List
where CAP#1 is a fresh type-variable:
CAP#1 extends Object from capture of ?
1 error
publicclassWildcardFixed {voidfoo(List<?> i) {fooHelper(i); }// Helper method created so that the wildcard can be captured// through type inference.private <T> voidfooHelper(List<T> l) {l.set(0,l.get(0)); }}
importjava.util.List;publicclassWildcardErrorBad {voidswapFirst(List<?extendsNumber> l1,List<?extendsNumber> l2) {Number temp =l1.get(0);l1.set(0,l2.get(0)); // expected a CAP#1 extends Number,// got a CAP#2 extends Number;// same bound, but different typesl2.set(0, temp); // expected a CAP#1 extends Number,// got a Number }}
在这个例子中,代码正进行不安全的操作。比如,看下面对于swapFirst函数的操作:
List<Integer> li =Arrays.asList(1,2,3);List<Double> ld =Arrays.asList(10.10,20.20,30.30);swapFirst(li, ld);
List <Integer>和List <Double>都满足条件List <?extends Number>,但是从Integer列表中取出一项并将其放入Double值列表中显然是不正确的。
使用Oracle's JDK javac编译器编译此段代码会产生如下报错:
WildcardErrorBad.java:7: error: method set in interface List<E> cannot be applied to given types;
l1.set(0, l2.get(0)); // expected a CAP#1 extends Number,
^
required: int,CAP#1
found: int,Number
reason: actual argument Number cannot be converted to CAP#1 by method invocation conversion
where E is a type-variable:
E extends Object declared in interface List
where CAP#1 is a fresh type-variable:
CAP#1 extends Number from capture of ? extends Number
WildcardErrorBad.java:10: error: method set in interface List<E> cannot be applied to given types;
l2.set(0, temp); // expected a CAP#1 extends Number,
^
required: int,CAP#1
found: int,Number
reason: actual argument Number cannot be converted to CAP#1 by method invocation conversion
where E is a type-variable:
E extends Object declared in interface List
where CAP#1 is a fresh type-variable:
CAP#1 extends Number from capture of ? extends Number
WildcardErrorBad.java:15: error: method set in interface List<E> cannot be applied to given types;
i.set(0, i.get(0));
^
required: int,CAP#1
found: int,Object
reason: actual argument Object cannot be converted to CAP#1 by method invocation conversion
where E is a type-variable:
E extends Object declared in interface List
where CAP#1 is a fresh type-variable:
CAP#1 extends Object from capture of ?
3 errors