• 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

Generics: problem with Lists when using wildcards

 
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello,

I have read about Generics and used them in my code as well. I am now trying to use Wildcards and have a problem. I have the following example.



I solved the first error as follows:



However I cannot understand how to solve the second one. What I want is to be have a list that can contain any Animal (Dogs and Cats).

I must be doing something wrong but I cannot understand what!

 
Simon Joseph Aquilina
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Solved ...

Was over complicating things. Here is my working version.

 
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If you've got a List<? extends Animal> reference, then you know it references a List of a specific type that is Animal or a subclass. Which means it can be a List<Animal>, a List<Dog>, a List<Cat>, a List<Snake> etc. So what can you safely add into all those? Nothing.

If you want a List that you can add any Animal to, then what you want is simply a List<Animal>. If you want a reference that can hold any List that can definitely contain any Animal, then the most general type is List<? super Animal> (which can reference either a List<Object> or List<Animal>).

The important point here - and it explains the problem you were originally having - is that wildcards only apply to references. The actual List has a specific type. When you wrote new ArrayList<>(), it would actually be interpreted as new ArrayList<Animal>().
 
After some pecan pie, you might want to cleanse your palatte with this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic