Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

The use of ? extends

 
Timothy Sam
Ranch Hand
Posts: 751
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From http://blogs.infosupport.com/martinw/articles/generics.aspx



I don't quite get it. What's the use of ? extends Animal if you can't make anything useful with it(based on the above example)?. Could you please explain this further? Thanks!
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You cannot add anything to the Collection, but you can iterate through it.

Using ? super does allow some things to be added.
 
cathy liu
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You cannot add anything to the Collection, but you can iterate through it.
==> Yes I agree with this.
Using ? super does allow some things to be added.
==> Not sure what do yu mean by this? Could you please explain it more? I am really confused with the "?". I thought when the ? is used in the type, nothing could be added at all, because the type is uncertain.

Thanks for your help in advance.
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Timothy Sam
Ranch Hand
Posts: 751
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hmmm... So would this work?

ArrayList<? extends Animal> animalList;

ArrayList<Dog> dogList = new ArrayList<Dog>();

dogList.add( new Dog() );

animalList = dogList;


and then, as you said... I can iterate through a List that has ? extends. Is this right?
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, you can do that, but you won't be able to add to animalList.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic