• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generics: problem with Lists when using wildcards

 
Simon Joseph Aquilina
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
  • 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
  • Quote
  • Report post to moderator
Solved ...

Was over complicating things. Here is my working version.

 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • 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>().
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic