Win a copy of Cloud Native PatternsE this week in the Cloud forum
or Natural Language Processing in the AI/ML forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Knute Snortum
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Ron McLeod
  • Piet Souris
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Frits Walraven
  • Ganesh Patekar

question from generics.

 
Ranch Hand
Posts: 46
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


My question: at line 16 the type of List is "Child". So why is that when am passing to it n11 method which would take Child collection or anything super to it(line 4), generates an error?

error:
ParentGenerics.java:21: n11(java.util.List<? super Child>) in ParentGenerics cannot be applied to (java.util.List<capture#880 of ? super Dog>)
p.n11(ml);
^
1 error

 
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your List may be a List<Child>, but it's reference type is List<? super Dog>. Which means that at line 19, as far as the compiler is concerned, it could be a List<Dog>. And the method won't accept one of those, will it?

When using generic wildcards, the important thing to remember is that the compiler will only allow things it can guarantee to be safe.
 
Ranch Hand
Posts: 100
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
At compile time, compiler cannot be sure of what you will instantiate the list with.



Compiler will only guess that the instantiation type will be either
Dog or Child or Object.
Compiler is not sure.
So the compiler thinks that you can instantiate the list m1 with a Dog list

and when you are passing m1 to method n11, compiler thinks that list m1 can be a Dog, which doesn't satisfy the requirement of <? super Child>
So it will stop you

 
amit mandal
Ranch Hand
Posts: 46
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks guys. It was really helpful. The problem is resolved.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!