LinkedList的add方法(带超类型)并不是每件事都好吗?

Min*_*ine 1 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);
    }

}
Run Code Online (Sandbox Code Playgroud)

Thi*_*ilo 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
Run Code Online (Sandbox Code Playgroud)

因为List<? extends X>你只能得到对象,但不能添加它们.相反,对于a,List<? super X>你只能添加对象,但不能将它们取出(你可以得到它们,但只能作为Object而不是X).

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

Number[] a = new Integer[1];
a[0] = 1;  // okay
a = new Double[1];
a[0] = 1;  // runtime error
Run Code Online (Sandbox Code Playgroud)

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

ShadeRect sr = new ShadeRect();
List<shape> list = new LinkedList<shape>();       
list.add(0,sr);
Run Code Online (Sandbox Code Playgroud)