• Post Reply Bookmark Topic Watch Topic
  • New Topic

Wildcards in Generics  RSS feed

 
adithya narayan
Ranch Hand
Posts: 79
Android Eclipse IDE Firefox Browser
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4568
9
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 377
Android Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
adithya narayan
Ranch Hand
Posts: 79
Android Eclipse IDE Firefox Browser
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!