• 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

Using ? super and wildcard

 
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In the code below I was surprised that I couldn't add an Animal to the List at the line indicated in the comment.

Can anyone clarify the rules here? From what I could see it is legal to pass any kind of list of objects where these objects are Dogs or supertypes of Dog, but it is only legal to add an actual Dog to the list.

So where we say ? super <class> can I assum the general rule that I can only add <class> objects to the collection even though the collection may be typed on a super type?

Or has something else gone wrong?

Thanks,
Tom

 
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public void addAnimal2(List<? super Dog> animals)

For this function declaration, you can pass Dog or any of its super types.
But inside the function you can add only Dog or its subtypes.
 
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
why animals.add(new Animal()) is not allowed ?

if animals is pointing to new ArrayList<Dog>() and try to add new Animal() will lead to run time exception.
only lower bound class object only can be added in the animals reference.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic