File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generics <? extends String> Question

 
Tepih Taskuhwilly
Greenhorn
Posts: 6
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4549
8
Java Netbeans IDE Scala
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2700
IntelliJ IDE Opera
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Manjusha Muraleedas
Ranch Hand
Posts: 52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I just tried to execute the following code ...

But I am getting compile time Error:




What this error means... ?
 
Wouter Oet
Saloon Keeper
Posts: 2700
IntelliJ IDE Opera
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic