This week's book giveaway is in the Android forum.
We're giving away four copies of Head First Android and have Dawn & David Griffiths on-line!
See this thread for details.
The moose likes Java in General and the fly likes Generics <? extends String> Question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Head First Android this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Generics <? extends String> Question" Watch "Generics <? extends String> Question" New topic

Generics <? extends String> Question

Tepih Taskuhwilly

Joined: May 28, 2009
Posts: 6
Why can I define generic List of anything that extends java.lang.String if String is a final class?

* method accepting list of objects instantiated from anything that extends the string
* @param args
* @return
public List<? extends Object> getAsAnyList(List<? extends String> args, boolean recurse) {
if (recurse) {
// this is just the check to see if string is acceptable too
List<String> lists=new LinkedList<String> ();
return getAsAnyList(lists, false);

return args;
Matthew Brown

Joined: Apr 06, 2010
Posts: 4537

Probably because it would be adding complexity for no gain for the compiler to check the extensibility of classes when you use "? extends".
Wouter Oet
Saloon Keeper

Joined: Oct 25, 2008
Posts: 2700

It is valid because it allows subclasses of String or the String class itself.

Please UseCodeTags when posting code. It will highlight your code and make it much easier to read. It probably will also increase the number of people helping you. You can edit your post with the button.

"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
Manjusha Muraleedas
Ranch Hand

Joined: Jun 02, 2010
Posts: 52
I just tried to execute the following code ...

But I am getting compile time Error:

What this error means... ?
Wouter Oet
Saloon Keeper

Joined: Oct 25, 2008
Posts: 2700

That is because you can only use a concrete class as type. Super or extends only works as a reference type. You can look at the generics tutorial for more information.
Manjusha Muraleedas
Ranch Hand

Joined: Jun 02, 2010
Posts: 52
Thank you Wouter Oet... i got the results.

Two mistakes:

1.Wild Cards cannot be used during Object creation
2.List need to be casted to ArrayList.

I agree. Here's the link:
subject: Generics <? extends String> Question
It's not a secret anymore!