Win a copy of TDD for a Shopping Website LiveProject this week in the Testing 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

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:
 
The airline is called "Virgin"? Don't you want a plane to go all the way? This tiny ad will go all the way:
free, earth-friendly heat - a kickstarter for putting coin in your pocket while saving the earth
https://coderanch.com/t/751654/free-earth-friendly-heat-kickstarter
reply
    Bookmark Topic Watch Topic
  • New Topic