aspose file tools
The moose likes Java in General and the fly likes Wildcards in Generics Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Wildcards in Generics" Watch "Wildcards in Generics" New topic
Author

Wildcards in Generics

adithya narayan
Ranch Hand

Joined: Jan 05, 2009
Posts: 76

Hi,

This is the sample piece of program i am working on :



At the Erroneous line i am getting the following error :
Type mismatch: cannot convert from element type capture#1-of ? super Dog to Animal

I changed the argument generic type from to ,so that while adding Dogs to the list the compiler wouldn't give me any compilation error but now when i am trying to iterate through the collection i am facing the specified problem !

Can anyone please explain this peculiar behavior ?


Thanks,
Adithya.
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 3862
    
    1

Your List<? super Dog> could be a List<Object>, couldn't it? Object is the supertype of all classes. So not everything in the list is guaranteed to be an Animal.

If you want to be able to add any Animal to a list, and you also want to guarantee that everything in the list is an Animal...then what you need is a List<Animal>. Generics aren't any use to you here.
Sean Clark
Rancher

Joined: Jul 15, 2009
Posts: 377

Hey,

I think my first question to you is to ask why does your "generic" method not take in a List<Animal> as both the method name and variable name suggest.

Secondly to answer your question you cannot know that everything in the list List<? super Dog> is an Animal and as such you can't just convert it. For example it could be of type java.lang.Object or any other superclass that Animal may have.

[edit - beaten to it ]

Sean

I love this place!
adithya narayan
Ranch Hand

Joined: Jan 05, 2009
Posts: 76


Post Today 3:08:22 PM Subject: Wildcards in Generics
Hey,

I think my first question to you is to ask why does your "generic" method not take in a List<Animal> as both the method name and variable name suggest.


I was trying to understand what all happens when you change something in the generic type when it comes to wildcards

Thanks for your replies Sean Clark and Matthew Brown.


Adithya.
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Wildcards in Generics
 
Similar Threads
ArrayList and List
Generics Help please !
Doubt in K&B SCJP 5: topic Generics
Chapter 7 - Objective 6.3 & 6.4 - type parameter for method checkAnimals () method.
Generics question from bonus exam