tags:

views:

41

answers:

1
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);
    }

}
+5  A: 

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);
Thilo
Thank you , excellent answer.....
MineIsMine
+1 - Nice explanation.
johnbk