链接列表的添加方法(带超类型)并不是一切都好吗?

时间:2010-10-13 05:45:38

标签: java generics

package pkg_2;

import java.util.*;

class shape{}

class Rect extends shape{}

class circle extends shape{}

class ShadeRect extends Rect{}

public class OnTheRun {

    public static void main(String[] args) throws Throwable {
        ShadeRect sr = new ShadeRect();
        List<? extends shape> list = new LinkedList<ShadeRect>();       
        list.add(0,sr);
    }

}

1 个答案:

答案 0 :(得分:6)

您无法向List<? extends X>.

添加任何内容

由于您不知道组件类型,因此无法允许add。考虑以下情况:

List<? extends Number> a = new LinkedList<Integer>();
a.add(1);  // in this case it would be okay
a = new LinkedList<Double>();
a.add(1);  // in this case it would not be okay

对于List<? extends X>,您只能获取对象,但不能添加它们。 相反,对于List<? super X>,您只能添加对象,但不能将它们取出(您可以获取它们,但只能作为对象,而不是X)。

此限制修复了数组的以下问题(允许这些“不安全”分配):

Number[] a = new Integer[1];
a[0] = 1;  // okay
a = new Double[1];
a[0] = 1;  // runtime error

至于你的程序,你可能只想说List<shape>。您可以将形状的所有子类放入该列表中。

ShadeRect sr = new ShadeRect();
List<shape> list = new LinkedList<shape>();       
list.add(0,sr);