• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Question on Generics

 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 329
Oracle Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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> .
 
You had your fun. Now it's time to go to jail. Thanks for your help tiny ad.
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic