• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Wildcard generic error in a Collection

 
Ranch Hand
Posts: 101
Netbeans IDE Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Bartender
Posts: 4568
9
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic