Generics again

S

Sierra Bravo

Given that "Programmer" and "SportsPerson" are both derived from
"Person", why doesn't the following fragment compile? The error is:
------------
Gen.java:50: cannot find symbol
symbol : method add(Person)
location: interface java.util.List<capture of ? extends Person>
someguy.add(p1);
-----------

In particular,
* what is "capture of ? extends Person"?
* what is the functional difference between the following two usages?

List<? extends Person> someguy = new ArrayList<Programmer>();
List<Programmer> someguy = new ArrayList<Programmer>();

TIA

sb
----------------------------------------------
public class Gen {
List<Person> anyguy = new ArrayList<Person>();
List<? extends Person> someguy = new ArrayList<Programmer>();
Person p1,p2,p3;

public void go() {
p1 = new Programmer("Ritchie");
p2 = new Programmer("Thompson");
p3 = new SportsPerson("Williams");

anyguy.add(p1);
anyguy.add(p2);
anyguy.add(p3);
someguy.add(p1);
someguy.add(p2);
someguy.add(p3);
}

public static void main(String s[]) {
(new Gen()).go();
}
}
 
R

Roedy Green

C

Chris Smith

Sierra Bravo said:
Given that "Programmer" and "SportsPerson" are both derived from
"Person", why doesn't the following fragment compile? The error is:
------------
Gen.java:50: cannot find symbol
symbol : method add(Person)
location: interface java.util.List<capture of ? extends Person>
someguy.add(p1);
-----------

You have a reference of type List<? extends Person>. From the
compiler's standpoint, that could point to an object of class
List<Person>, or perhaps List<Programmer>, or perhaps
List<SportsPerson>. It doesn't really know which. So, when you try to
add a Programmer to the list (for example), it isn't safe... because the
list MIGHT be a List<SportsPerson>, in which case adding the programmer
is an error. The type of the reference is the ONLY place the compiler
looks to do this kind of reasoning, and the wildcard type does not
guarantee that the operation is safe.

For this reason, in order to invoke add on a List, you need to have a
lower bound, either by specifying a specific type for the list
(List<Person> instead of List<? extends Person>) or by specifying a
lower bound explicitly (List<? super Programmer>, for example).

--
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top