我有外部泛型类,它有一些内部类,为此我想使用泛型类外部类。Java泛型类,使用外部类参数的内部类
但是,我不明白如何正确使用泛型参数。
实施例:
class Outer<E extends CharSequence>{
class Inner extends ArrayList<E>{
}
void func() {
ArrayList<CharSequence> al = new ArrayList<CharSequence>();
al.add("abc"); // OK
CharSequence a = al.get(0); // OK
Inner in = new Inner();
in.add("abc"); // Error: The method add(E) in the type ArrayList<E> is not applicable for the arguments (String)
CharSequence b = in.get(0); // OK
}
}
如何可以声明内部类使用相同的通用类型的外部类的? 感谢
编辑+解决方案:
最后我取得了我想要的东西,这里的示例结果:
abstract class MyGenericClass<E extends CharSequence>{
class TheList extends ArrayList<E>{};
TheList list = new TheList();
}
final class ClassInstance extends MyGenericClass<String>{
};
public class Main{
public static void main(String[] args){
ClassInstance c = new ClassInstance();
c.list.add("abc");
String s = c.list.get(0);
}
}
我的要求是有泛型类,也有它的通用容器,它将使用与其父类相同的类型参数。
注意:CharSequence/String是使用的示例参数,我的实际用法是不同的。
内的在FUNC的使用()是原始的,它应该是内在新=内(); –
@AllenParslow:错了。 'Inner'不是通用的。 – SLaks
'E'已经可以提供给你的班级。 –