Generics (? extends T)

Hi

Does

List<?extends A> lista =new ArrayList<B>();

make lista read-only?

I ask because given the following:

import java.util.List;

import java.util.ArrayList;

class A{}

class Bextends A{}

class Generics

{

publicstaticvoid main(String args[])

{

List<?extends A> lista =new ArrayList<B>();

List<B> listb =new ArrayList<B>();

lista.add(new A());// 1

lista.add(new B());// 2

listb.add(new B());// 3

}

}

only the add() in line 3 will compile.

Lines 1 and 2 cause a compiler error, viz:

Generics.java:15: cannot find symbol

symbol : method add(A)

location:interface java.util.List<capture#709 of ?extends A>

lista.add(new A());

^

Generics.java:16: cannot find symbol

symbol : method add(B)

location:interface java.util.List<capture#972 of ?extends A>

lista.add(new B());

^

2 errors

How can I use add() with a polymorphically-defined collection (i.e. using <? extends T>, or, is that I cannot? Seems odd that I can neither add an A nor a B to the ArrayList lista above.

Thanks.

[2313 byte] By [JasonLind_a] at [2007-11-26 21:09:45]
# 1
You can't add anything to such a list since the correct type is unknow at compile time.Details: Learning Java, page 235: http://www.oreilly.com/catalog/learnjava3/chapter/ch08.pdf
prometheuzza at 2007-7-10 2:45:48 > top of Java-index,Java Essentials,New To Java...
# 2

> You can't add anything to such a list since the

> correct type is unknow at compile time.

>

> Details: Learning Java, page 235:

> http://www.oreilly.com/catalog/learnjava3/chapter/ch08

> .pdf

So the answer is yes, declaring such a reference makes the object that it points to read-only, as stated in the pdf.

Thanks.

JasonLind_a at 2007-7-10 2:45:48 > top of Java-index,Java Essentials,New To Java...
# 3
> So the answer is yes, declaring such a reference> makes the object that it points to read-only, as> stated in the pdf. > > Thanks.You're welcome.
prometheuzza at 2007-7-10 2:45:48 > top of Java-index,Java Essentials,New To Java...
# 4

> > You can't add anything to such a list since the

> > correct type is unknow at compile time.

> >

> > Details: Learning Java, page 235:

> >

> http://www.oreilly.com/catalog/learnjava3/chapter/ch08

>

> > .pdf

>

> So the answer is yes, declaring such a reference

> makes the object that it points to read-only

No, it doesn't make the object read only. It just means you can't call methods that require the type parameter to be known. If there were an unparameterized add() method, you could call that, and you can certainly call clear(). The language has no notion of "read-only" objects.

jverda at 2007-7-10 2:45:48 > top of Java-index,Java Essentials,New To Java...
# 5
@OP: this compiles and runs correctly:List<? extends A> list = new ArrayList<A>();list.add(null);
prometheuzza at 2007-7-10 2:45:48 > top of Java-index,Java Essentials,New To Java...