wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Generics: problem with Lists when using wildcards Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Generics: problem with Lists when using wildcards " Watch "Generics: problem with Lists when using wildcards " New topic
Author

Generics: problem with Lists when using wildcards

Simon Joseph Aquilina
Ranch Hand

Joined: Feb 14, 2006
Posts: 102
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

Joined: Feb 14, 2006
Posts: 102
Solved ...

Was over complicating things. Here is my working version.

Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4422
    
    8

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>().
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Generics: problem with Lists when using wildcards