This week's book giveaway is in the Design forum.
We're giving away four copies of Building Microservices and have Sam Newman 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 Building Microservices this week in the Design 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: 88

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: 4541

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.
Have you checked out Aspose?
subject: Wildcard generic error in a Collection
It's not a secret anymore!