Last week, we had the author of TDD for a Shopping Website LiveProject. Friday at 11am Ranch time, Steven Solomon will be hosting a live TDD session just for us. See for the agenda and registration link
  • 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
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

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>().
 
brevity is the soul of wit - shakepeare. Tiny ad:
free, earth-friendly heat - a kickstarter for putting coin in your pocket while saving the earth
https://coderanch.com/t/751654/free-earth-friendly-heat-kickstarter
reply
    Bookmark Topic Watch Topic
  • New Topic