以下代码无法在 Eclipse 中编译。它说“Abc 类型的 putHelper(List,int,E) 方法不适用于参数 (List <.capture#8-of extends E>",int,E)"
private <E> void putHelper(List<E> list, int i, E value) {
list.set(i, value);
}
public <E> void put(List<? extends E> list, int toPos, E value) {
// list.set(toPos,value);
putHelper(list, toPos, value);
}
我不明白为什么会这样?因为下面的代码工作正常。
public <E> void put(List<? extends E> list,int fromPos, int toPos) {
putHelper(list,fromPos,toPos);
}
private <E> void putHelper(List<E> list,int i, int j) {
list.set(j,list.get(i));
}
而且我知道这里的辅助方法能够捕获通配符类型,但是为什么不能在早期的代码中呢?
编辑:在第三种情况下,如果我将 put 方法中的类型参数更改为 List<.? super E> 并且当我尝试从另一个采用列表的方法调用 put() 方法时,Eclipse 不会编译它。它说,“Abc 类型的 put(List<.? super E>,int,E) 方法不适用于参数 (List <.capture#6-of extends E>",int,E)"
public static <E> void insertAndProcess(List<? extends E> list) {
// Iterate through the list for some range of values i to j
E value = list.get(i);
//Process the element and put it back at some index
put(list, i+1, value);
//Repeat the same for few more elements
}
private static <E> void putHelper(List<E> list, int i, E value) {
list.set(i, value);
}
public static <E> void put(List<? super E> list, int toPos, E value) {
putHelper(list, toPos, value);
}
在这里,insertAndProcess() 如何调用 put() 方法并在其实现中使用它,而用户仍然可以使用 ArrayList<.Integer> 调用这两个方法?