Possible Duplicate:
IsList<Dog>
a subclass ofList<Animal>
? Why aren't Java's generics implicitly polymorphic?
I have a List of class Dogs which extends Animals and have a List of the following type.
ArrayList<Animals> animal = new ArrayList<Animals>();
Now I have another class, Puppy, which extends Dogs.
And have a List<Puppy> puppy = new ArrayList<Puppy>();
Now I want to cast list animal
to puppy
. Is it possible to do directly?
I can do it as below.
for (Animals ani: animal){
puppy.add((Puppy) ani)
}
But I want a direct casting solution. Is it possible?
No it will not work directly except you define your first list as:
List<? extends Animals> animal;
then you will be able to do:
List<Puppy> puppy = new ArrayList<Puppy>();
animal = puppy;
First you have to define your list in base class as...
public ArrayList<? super Animal> ani;
then cast your base class list in extends class as ...
ArrayList<? extends Animal> puppy= new ArrayList<Puppy>();
puppy= (ArrayList<? extends Animal>)ani;
List<Puppy> castPuppy = (List<Puppy>)puppy;//here we case the base class list in to derived class list.
Note: it might through unchecked exception
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With