• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Tim Cooke
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Knute Snortum
  • paul wheaton
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Ron McLeod
  • Piet Souris
  • Ganesh Patekar
Bartenders:
  • Tim Holloway
  • Carey Brown
  • salvin francis

The use of ? extends

 
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!
 
Ranch Hand
Posts: 2410
  • 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.
 
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: 2410
  • 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: 2410
  • 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.
 
There’s no place like 127.0.0.1. But I'll always remember this tiny ad:
professionally read, modify and write PDF files from Java
https://products.aspose.com/pdf/java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!