Two Laptop Bag
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Generics question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Generics question" Watch "Generics question" New topic

Generics question

Saroja Penn

Joined: Nov 03, 2007
Posts: 3
An ArrayList<Animal> can accept references of type Dog, Cat, or any other
subtype of Animal (subclass, or if Animal is an interface, implementation).

The above line is from the 2-minute drill of Generics chapter.

Could anyone please explain what this means? I cannot follow what it says. I thought List<Animal> takes only List<Animal>. Please explain with a small example.

Appreciate any help
Thank you.
Kelvin Chenhao Lim
Ranch Hand

Joined: Oct 20, 2007
Posts: 513
It's referring to the elements that you can insert into the list object. You can put any Animal object, including subclass instances, into an List<Animal>.

But you're correct that a List<Animal> reference variable can only be safely assigned a List<Animal> object.

SCJP 5.0
Saroja Penn

Joined: Nov 03, 2007
Posts: 3
Thank you, Kelvin.

Its clear now.
I agree. Here's the link:
subject: Generics question
It's not a secret anymore!