5

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?

YoYo
  • 9,157
  • 8
  • 57
  • 74
RTA
  • 1,251
  • 2
  • 14
  • 33
  • Define "direct casting solution"? – Michael Robinson May 11 '12 at 08:51
  • 1
    If you have a List of Animals that are actually Dogs and you want to handle Dogs and not Animals then why is your list a list of Animals? – Jean Logeart May 11 '12 at 08:55
  • Following on from Vakimshaar's comment, if your code requires a lot of dangerous casting like this (may cause exceptions), then you should probably rethink your code. E.g. instead of adding puppy like so, call a method that is inside the Animal's class that adds them to the appropriate list... overriding that method for each subclass – Perry Monschau May 11 '12 at 08:57
  • there is nothing dangerous about this cast @PerryMonschau – Enerccio May 13 '21 at 05:48

2 Answers2

16

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;
UVM
  • 9,776
  • 6
  • 41
  • 66
sebastian
  • 2,427
  • 4
  • 32
  • 37
1

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

RTA
  • 1,251
  • 2
  • 14
  • 33
  • 3
    If "ani" does not actually contain Puppy objects, then this approach is dangerous. The compiler won't complain but the puppy variable will actually contain references to Animal objects. Any attempt to use them as "Puppies" will cause exceptions. In other words `castPuppy.get(0) instanceof Puppy` will be false! Moreover, `Puppy p = castPuppy.get(0)` will throw a runtime exception! – gMale Jun 29 '13 at 04:56