aspose file tools*
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
JavaRanch » Java Forums » Java » Java in General
Bookmark "Generics <? extends String> Question" Watch "Generics <? extends String> Question" New topic
Author

Generics <? extends String> Question

Tepih Taskuhwilly
Greenhorn

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
Bartender

Joined: Apr 06, 2010
Posts: 4363
    
    8

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.


 
Don't get me started about those stupid light bulbs.
 
subject: Generics <? extends String> Question