日期:2014-05-20  浏览次数:20764 次

求助:关于Java泛型通配符
和各位请教一个关于泛型通配符的问题,以下是程序:
import java.util.*;
import java.io.*;

class A
{
int a;
public A()
{
a=5;
}
}

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)
这其中的原因是什么,请高人指点迷津,非常感谢!
------解决方案--------------------
引用:
B是A的子类,所以ArrayList<A>是ArrayList<? super B>的子类


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,

所以当你调用 list2 的 get(int) 方法的时候,返回值只能用 Object 来接