• Post Reply Bookmark Topic Watch Topic
  • New Topic

Problem with generics wildcards  RSS feed

 
Ranch Hand
Posts: 103
Eclipse IDE Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a superclass Animal, and two subclasses Dog and Cat that extend the Animal super class.
I have a method signature of the type -----> void aMethod(List<? super Dog> myList)

Now if i have a list of the Following format------> List<Animal> testList=new ArrayList<Animal>();

Then i can pass testList into aMethod, because of the <? super Dog> wildcard.

However, inside aMethod, i can write something like this------> myList.add(new Cat()); as i have taken an Animal List and Cat extends Animal, so polymorphism holds.

Can you please tell me where my concept is going wrong in generics regarding this, because in general to prevent this kind of entries, we cant pass a List<Dog> into a List<Animal>..Please help !!! I am confused.....
 
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'd suggest trying it out. You'll find one part of what you're suggesting won't compile - that's how the compiler protects you. If it still doesn't make sense at that point, we can explain!
 
jishnu dasgupta
Ranch Hand
Posts: 103
Eclipse IDE Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Okay will give it a try !!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!