Win a copy of Java 9 Modularity: Patterns and Practices for Developing Maintainable Applications this week in the Java 9 forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

List<?> , List<T>  RSS feed

 
Muhammad Rehan
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
 
Henry Wong
author
Sheriff
Posts: 23289
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor 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
Sheriff
Posts: 23289
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor 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
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!