Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast the sub class List to base class List [duplicate]

Tags:

java

Possible Duplicate:
Is List<Dog> a subclass of List<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?

like image 960
RTA Avatar asked May 11 '12 08:05

RTA


2 Answers

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;
like image 192
sebastian Avatar answered Sep 22 '22 23:09

sebastian


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

like image 20
RTA Avatar answered Sep 23 '22 23:09

RTA