Question

I declares collection so

 List<? extends Number> ml = new Vector<Integer>();

I try to add element

It is not valid :

ml.add(new Integer(1));

it is too

ml.add(new Object());

I very confused. How can I use ml?

Was it helpful?

Solution

Lists are not covariant. If you use ? extends Number then you can only read from the list, you can't write to it. Why not?

m1.add(new Object());

It should be obvious why this doesn't work. The list is supposed to contain Numbers and an Object is not a Number.

ml.add(new Integer(1));

This one's not so obvious. Imagine that you had a different instantiation of m1:

List<? extends Number> ml = new Vector<Double>();
ml.add(new Integer(1));

Now m1 is a vector of doubles. Adding an integer to this list would be illegal. The compiler doesn't in general know what the concrete type of ? extends Number is. To be conservative, it disallows calling the add method entirely. You can iterate over the list and read what's in it, and you can delete items from it, but you can't add new items to it.

Or to put it another way, for List<E> you can call methods that return E but you can't call ones that take E as a parameter.

OTHER TIPS

You can't call methods parameterized with an upper-bounded wildcard. No type can satisfy that wildcard except the capture of the wildcard itself.

list.add(E e)

ends up as

list.add(<capture-of ? extends Number> e)

There's no capture happening on the type of your variable ml.

Here you are declaring ml as a generic List. Since you are using a wildcard, you can only know that the actual type of the contained objects might be a Number or one of it's subtype. But the JVM doesn't really know what exactly this type is. Thus, this declaration makes ml to be a read-only List. That's why you cannot add any element in it, just get and read them. Change it to: List

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top