class B extends A implements Serializable
{
int b;
public B()
{
super();
b=15;
}
}
public class Test
{
public static void main(String[] args)
{
ArrayList<A> list1=new ArrayList<A>();
ArrayList<? super B> list2=list1;
list2.add(new A());
list2.add(new B());
}
}
上述程序中,语句"list2.add(new A());"出错,编译器提示:
The method add(capture#1-of ? super B) in the type ArrayList<capture#1-of ? super B> is not applicable for the arguments (A)
这其中的原因是什么,请高人指点迷津,非常感谢! ------解决方案--------------------
ArrayList<A>和ArrayList<? super B>之间没有继承关系,
ArrayList<? super B> list=new ArrayList<A>(); 编译通过是因为泛型的语法就是这样支持的,
<? super B> 表示“B的某种父类型”,
在无法确定“某种”究竟是“哪种”的情况下,
可以确定是<? super B>的“子类型”的只有 B 和 B的子类型
(“子类型”加引号,准确的说法是“符合条件的类型”)
------解决方案-------------------- 多说一句,
<? super B> 表示“B的某种父类型”,
同理,在无法确定“某种”究竟是“哪种”的情况下,
可以确定是<? super B>的“父类型”的只有Object,