This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan 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 Android Security Essentials Live Lessons this week in the Android 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

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. unexpected type
found : ? extends Items
required: class or interface without bounds
ArrayList<? extends Items> l = new ArrayList<? extends Items>();
^ 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

Joined: Apr 06, 2010
Posts: 4343

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