| Author |
Just came across a statement public void takeList(List<? extends String) list {}
|
Vishal Hegde
Ranch Hand
Joined: Aug 01, 2009
Posts: 984
|
|
|
Just came across a statement public void takeList(List<? extends String) list {} what does the ? mean in here
|
http://www.lifesbizzare.blogspot.com || OCJP:81%
|
 |
Maneesh Godbole
Saloon Keeper
Joined: Jul 26, 2007
Posts: 8547
|
|
It means the List will accept any element which subclasses String.
More on generics wildcards here http://download.oracle.com/javase/tutorial/extra/generics/wildcards.html
But remember, can one subclass String?
|
[Donate a pint, save a life!] [How to ask questions] [Onff-turn it on!]
|
 |
Vishal Hegde
Ranch Hand
Joined: Aug 01, 2009
Posts: 984
|
|
Thankyou with respect to this question i want to know why
list.add("Foo") when added within the method wont compile
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32827
|
|
|
I don't think you can add to anything taking <?....> as an actual type parameter.
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16809
|
|
Just trying to be precise, so feel free to ignore. It is the method will take any List that accepts a particular type that is string or subclasses string. It is not the list that accepts any type, the list accepts a specific type.
Now, of course, this example is somewhat silly. Since the String class is final, there are no classes that subclasses string; And the compiler is not smart enough to flag this.
Henry
|
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19230
|
|
Campbell Ritchie wrote:I don't think you can add to anything taking <?....> as an actual type parameter.
With <? super X> you can add anything that IS-A X. With <? extends X> you can only add null.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32827
|
|
|
Thank you for sorting that out Rob. You can only add null to a Collection<? extends Foo>.
|
 |
Mike Simmons
Ranch Hand
Joined: Mar 05, 2008
Posts: 2815
|
|
Henry Wong wrote:Now, of course, this example is somewhat silly.
Somewhat. I think they may be intentionally using the <? extends X> idiom to signal that the list is not intended to be modified, only read. This discourages (though it does not necessarily prevent) people from modifying the List. Not very elegant, but some people do use it this way.
|
 |
 |
|
|
subject: Just came across a statement public void takeList(List<? extends String) list {}
|
|
|