This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
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: 4339
    
    7

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.
 
jQuery in Action, 2nd edition
 
subject: Wildcard generic error in a Collection
 
Similar Threads
EL Mystery
How can we search a name with a regex like "%" in a list of values
Set that only Items can be added
Problem While Removing Element From List
Generics doubt