Search...
FAQs
Subscribe
Pie
FAQs
Recent topics
Flagged topics
Hot topics
Best topics
Search...
Search within Beginning Java
Search Coderanch
Advance search
Google search
Register / Login
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
Jeanne Boyarsky
Ron McLeod
Liutauras Vilda
Paul Clapham
Sheriffs:
paul wheaton
Tim Cooke
Henry Wong
Saloon Keepers:
Stephan van Hulst
Tim Holloway
Carey Brown
Frits Walraven
Piet Souris
Bartenders:
Mike London
Forum:
Beginning Java
how to pass a child list to a parentlist
chaohua wang
Ranch Hand
Posts: 62
posted 12 years ago
Number of slices to send:
Optional 'thank-you' note:
Send
hi Folks,
I have a
cat class , its super class is animal class.
cat extends animal{
}
i got a cat list:
List<cat> catlist= task.getCatList();
I need to pass this catlist to a method:
public takeCareOfAllanimals (List<animal> animals).
I am not sure how to do this? I tied to cast catlist to (animal)catlist, but it doesn't allow me.
thank you
Chwang
Paul Clapham
Marshal
Posts: 27536
88
I like...
posted 12 years ago
1
Number of slices to send:
Optional 'thank-you' note:
Send
You can't do that. Here's why:
List<Cat> cats = getAListOfCats(); // Here we have a list of animals which are guaranteed to be Cats. List<Animal> animals = cats; // As you know this is not legal, but let's suppose it was. animals.add(0, new Rabbit()); // Here we added a Rabbit to the beginning of the list. That's okay because it's just a list of Animals. Cat notACat = cats.get(0); // Here we get the first entry from the list. // But it's a Rabbit. Then we assign it to a Cat? That's a problem because we guaranteed the list only contains Cats.
So, no. List<Cat> is not a subtype of List<Animal>.
You should
be doing this:
public takeCareOfAllanimals (List<? extends Animal> animals)
chaohua wang
Ranch Hand
Posts: 62
posted 12 years ago
Number of slices to send:
Optional 'thank-you' note:
Send
Paul,
I see, Thank you very much for the excellent explanation.
Best Regards,
Chwnag
Campbell Ritchie
Marshal
Posts: 77249
371
posted 12 years ago
Number of slices to send:
Optional 'thank-you' note:
Send
Look through the
Java™ Tutorials
; there are two sections on generics, which should help you. Also Google for
Angelika Langer Java Generics FAQ
.
reply
reply
Bookmark Topic
Watch Topic
New Topic
Boost this thread!
Similar Threads
Question about generics
SCJP Generics Question
Generics
How do I convert a list of list into array [] []
Generics doubt ?
More...