开发者

the add method of LinkedList (with supertype) isn't every thing alright?

开发者 https://www.devze.com 2023-01-19 15:29 出处:网络
package pkg_2; import java.util.*; class shape{} class Rect extends shape{} class circle extends shape{} class ShadeRect extends Rect{}
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);
    }

}
开发者_开发知识库


You cannot add anything to a List<? extends X>.

The add cannot be allowed because you do not know the component type. Consider the following case:

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

For List<? extends X> you can only get out objects, but not add them. Conversely, for a List<? super X> you can only add objects, but not get them out (you can get them, but only as Object, not as X).

This restriction fixes the following problems with arrays (where you are allowed these "unsafe" assigns):

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

As for your program, you probably just want to say List<shape>. You can put all subclasses of shape into that list.

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

精彩评论

暂无评论...
验证码 换一张
取 消