Win a copy of Five Lines of Code this week in the OO, Patterns, UML and Refactoring forum!
  • 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
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Carey Brown

List<?> , List<T>

 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am unable to understand unbounded wildcards in generics.
Consider this example

.

As per my understanding arraylist is of type string and it can contain string.

Can anyone please explain it to me (the concept);

Thanks,
Rehan
 
author
Posts: 23878
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Muhammad Rehan wrote:
As per my understanding arraylist is of type string and it can contain string.



You are correct, in that an ArrayList<String> instance is a collection that contains strings... but ... how would the compiler know that?  To the compiler, all it is, is an instance of something that implements the List interface, with an unknown generic.

So, if you were the compiler, would you allow a string to be added to an instance of something that implements the List interface, with an unknown generic?

Henry
 
Muhammad Rehan
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks henry,

But  then why this kind of declaration is allowed?

Is it for only methods then like



Regards,
Rehan
 
Henry Wong
author
Posts: 23878
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Muhammad Rehan wrote:
But  then why this kind of declaration is allowed?



Well, to turn it around ... why should the code be *not* allowed?

Yes, I agree that you created code that, (1) ends up with a single reference to a collection, (2) where the reference doesn't have knowledge of the generic type, and (3) the collection is empty. This mean that there is little that you can do with the collection, except perhaps, add() a null reference. So, in other words, you created code that is pretty useless.

So, why should it not be allowed? And if it was not allowed, then what about the infinite other useless code that can be churned out? ...

Henry
 
Consider Paul's rocket mass heater.
    Bookmark Topic Watch Topic
  • New Topic