File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
A friendly place for programming greenhorns!
Big Moose Saloon
Register / Login
Programmer Certification (SCJP/OCPJP)
Question on Generics
Joined: Nov 22, 2008
Sep 10, 2007 18:03:00
I have a question on Generics from K&B book page 596.
Which of them are legal declarations ? 1) List<?> list=new ArrayList<Dog>(); 2) List<? extends Animal> list=new ArrayList<Dog>(); 3) List<?> foo=new ArrayList<? extends Animal>(); 4) List<? extends Dog>clist= new ArrayList<Integer>(); 5) List<? super Dog>blist=new ArrayList<Animal>(); 6) List<? super Animal>dlist=new ArrayList<Dog>(); Correct Answers are 1,2,5
for the first one, we say List of Anytype can point to Dog arraylist. But is this not a potential problem creator? Does this not mean that Integer to refer Dog?
for the fifth one, we say any class Dog or any superclass of it can refer Animal.How is this possible? How can a Dog refer Animal?
for the sixth one, we say Animal or any superclass Animal to refer Dog. This makes sense as Animal refers Dog and any super class of animal too refers Dog.But in the book, it is not an option.
Please explain me on this.
Joined: May 10, 2007
Sep 10, 2007 22:56:00
That is safe because as 1) will not let you add anything to list,not even a Dog.In 5) also you can add only Dog and nothing else and Dog
Animal in this example.
SCJP 1.5<br />SCWCD 5.0
Joined: Mar 22, 2007
Sep 11, 2007 07:40:00
1) List<?> list=new
List<?> is read as �List of
�. It can refer to any kind of list. It is semantically equivalent to List<? extends Object> (i.e. any kind of list)
5) List<? super Dog>blist=new
List<? super Dog> is read as �List of any type that is Dog or a superclass of Dog�. It can refer to any of these: List<Dog>, List<Animal> and List<Object>.
6) List<? super Animal>dlist=new
List<? super Animal> is read as �List of any type that is Animal or a superclass of Animal�. It can refer to any of these: List<Animal> and List<Object>.
This is why it cannot refer to a list of Dog (List<Dog>
SCJP 1.4 (88%) - SCJP 5.0 Upgrade (93%) - SCWCD 1.4 (97%) - SCBCD 5.0 (98%)
I agree. Here's the link:
subject: Question on Generics
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter
| Powered by
Copyright © 1998-2014