我相信您正在寻找一种方法,该方法接受一个列表,向其中添加一些内容,然后返回该列表。该列表是通用的,您希望返回类型与参数的类型相匹配。
在一般情况下,您是这样做的:
public <T extends Parent> List<T> myfunction(List<T> myList) {
... // Add something to myList
return myList;
}
具体来说,您正在尝试将new Child() 添加到myList。这行不通。 myfunction() 可以用多种列表调用,而添加new Child() 只能在列表是List<Parent> 或List<Child> 时起作用。下面是一个不同类型列表的示例:
public static class Parent {}
public static class Child extends Parent {}
public static class OtherChild extends Parent {}
public <T extends Parent> List<T> myfunction(List<T> myList) {
myList.add(new Child());
return myList;
}
myfunction(new ArrayList<OtherChild>());
在最后一行中,myfunction() 使用 OtherChild 对象的列表调用。显然,将Child 对象添加到这样的列表中是非法的。编译器通过拒绝 myfunction() 的定义来防止这种情况发生
附录
如果您希望myfunction() 能够将元素添加到myList,则需要使用工厂(因为Java 不允许new T() 其中T 是类型参数-由于type erasure)。 myfunction() 应该是这样的:
public interface Factory<T> {
public T create();
}
public <T extends Parent> List<T> myfunction(List<T> myList,
Factory<? extends T> factory) {
myList.add(factory.create());
return myList;
}
现在,它的用法:
public static class ChildOfOtherChild extends OtherChild {}
myfunction(new ArrayList<OtherChild>(), new Factory<ChildOfOtherChild>() {
@Override public ChildOfOtherChild create() { return new ChildOfOtherChild(); }
});
}