想法是做类似下面的事情,让编译器在编译时检查 toLoad 是一个可以包含 AType 对象的数组(即:AType extends or is a T NOT T extends or is AType)。有没有办法用泛型做到这一点?
private List<AType> aList_;
<T superclassof AType> T[] loadArray(T[] toLoad) {
for(int i = 0; i < alist_.size(); ++i) {
toLoad[i] = (T)aList_.get(i);
}
最佳答案
不……Java 不允许类型变量的下限,即使有一些有效的用例……就像你的。
如果您使用 List
,我们可以使用带下界的通配符 List<? super A>
.但不适用于数组。
<L extends List<? super A> L load(L toLoad)
{
for(int i = 0; i < alist_.size(); ++i)
toLoad.set(i, aList_.get(i) );
return toLoad;
}
不过,我们可以将数组包装在列表中。
Object[] array = new Object[length];
load(new Wrapper<>(array));
class Wrapper<E> implements List<E>
{
E[] array;
Wrapper(E[] array){ this.array=array; }
E set(int index, E element)
{
check index<array.length
array[index] = element;
}
关于java - 是否有 "superclass of"方法来定义泛型类型或仅 "extends"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15284365/