• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Wildcard generic error in a Collection

 
Joey Sanchez
Ranch Hand
Posts: 88
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4568
9
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic