public interface Foo<E> {
public void blah(E e);
}
public class MyClass<E> {
private final Foo<E>[] fooArray = new Foo<E>[8]; // does not compile!
// (...)
}
解决该泛型限制的正确方法是什么?
或许它不是限制而我错过了什么?
答案 0 :(得分:2)
make-it-compile 方式是使用泛型声明变量,但使用原始类型初始化数组(不是元素):
//add @SuppressWarnings("unchecked") to avoid warnings
Foo<String>[] arrayOfFoo = new Foo[8];
arrayOfFoo[0] = new ClassThatImplementsFoo<String>();
//line below gives a compile error since the array declaration is for Foo<String>
//and won't allow Foo<AnotherClass>
arrayOfFoo[1] = new ClassThatImplementsFoo<Integer>();
更好更安全的方法是使用List
而不是普通数组:
List<Foo<String>> fooList = new ArrayList<Foo<String>>();
fooList.add(new ClassThatImplementsFoo<String>());
在您的代码中,您应该这样做:
public class MyClass<E> {
private final Foo<E>[] fooArray = new Foo[8];
// (...)
}