Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question on Generics

 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello All,

I have a question on Generics from K&B book page 596.



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.
 
Abhishek Kanchan
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ravi,
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 IS-A Animal in this example.
 
Sergio Tridente
Ranch Hand
Posts: 329
Java Linux Oracle
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1) List<?> list=new ArrayList<Dog>();

List<?> is read as �List of unknown�. 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 ArrayList<Animal>();

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 ArrayList<Dog>();

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> .
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic