Help coderanch get a
new server
by contributing to the fundraiser
  • 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Devaka Cooray
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Tim Moores
  • Carey Brown
  • Mikalai Zaikin
Bartenders:
  • Lou Hamers
  • Piet Souris
  • Frits Walraven

Generic Methods Help

 
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
in SCJP SCJD 1.6 Kathy Sierra & Bert Bates book page '615', there is a pragraph

(

We still have two questions…how do you get around it and why the heck does
the compiler allow you to take that risk for arrays but not for ArrayList (or any other
generic collection)?

)

it is telling us we have still two question
First "how do you get around it"
my question is exactly this sentence..

What does book want to express by this sentence (how do you get around it)
Please help...
 
Ranch Hand
Posts: 146
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The way to getting around with that is using a List of Animal so you can pass through your method which expects a List of animal.
The point is: you can't deal with polymorphism the same way to ordinary classes.
Base type (List, ArrayList) can be polymorphic as whatever class in java. But generic types can't be treated the same way.
If you really need to use something near to polymorphic generic types you will need to use wildcards with <? extends Something> or <? super Something>.

<? extends Something> you can't use add with collections
<? super Something> you can use add with collections

To see more about it take a look at Generics post from Suresh.

The code bellow is getting around this problem using a list of Animals:
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic