File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Wildcard generic error in a Collection Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Wildcard generic error in a Collection" Watch "Wildcard generic error in a Collection" New topic
Author

Wildcard generic error in a Collection

Joey Sanchez
Ranch Hand

Joined: Jun 23, 2011
Posts: 86

Make a subclass of Items. Create a method that takes only Items or the Items subclass. Prove it.




I got some errors that I can't resolve.

WildcardCollection.java:9: unexpected type
found : ? extends Items
required: class or interface without bounds
ArrayList<? extends Items> l = new ArrayList<? extends Items>();
^
WildcardCollection.java:10: cannot find symbol
symbol : method add(Items)
location: class java.util.ArrayList<capture#262 of ? extends Items>
l.add(new Items("hola",1));
^
Any Idea?
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4460
    
    8

There are two problems here.

1. You can't create an ArrayList<? extends Items>. Wildcards are for reference types - the actual object has to be of a specific type.

2. Once you've got an ArrayList<? extends Items> reference, you can't add anything (except null) to it. The actual type could be of any subclass of Items, and so there's no object that the compiler can guarantee can be safely added.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Wildcard generic error in a Collection