【发布时间】:2014-06-24 05:57:42
【问题描述】:
以下代码无法在 Eclipse 中编译。它说“Abc 类型的 putHelper(List,int,E) 方法不适用于参数 (List <.capture 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 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>调用这两个方法?
【问题讨论】:
标签: java generics compiler-errors bounded-wildcard helpermethods