sametbilgi
sametbilgi

Reputation: 602

Error when casting inside arraylist

I have three classes which

public abstract class Animal {
    ...
}

public abstract class Cat extends Animal {
    ...
}

public abstract class Dog extends Animal {
    ...
}

And if i want to create an animal arraylist with dogs and cats it gives runtime casting error.

List<Animal> animals = new ArrayList<>();
List<Cat> cats = new ArrayList<>();
List<Dog> dogs = new ArrayList<>();

animals.add((Animal) cats);
animals.add((Animal) dogs);

How can i create this arraylist?

Upvotes: 0

Views: 116

Answers (2)

AscendingEagle
AscendingEagle

Reputation: 838

"add" will just add one element (But not a List). You want to add all elements in a List so you need to use addAll():

List<Animal> animals = new ArrayList<>();
List<Cat> cats = new ArrayList<>();
List<Dog> dogs = new ArrayList<>();

animals.addAll(cats);
animals.addAll(dogs);

Upvotes: 4

Romeo Sierra
Romeo Sierra

Reputation: 1756

Your casting is wrong. With the casting in place, you are trying to assign somethings which are incompatible.

animals.add((Animal) cats);

When you say (Animal) cats, you are trying to cast an List<Cat> to Animal, which is wrong.

If it is adding all the elements in cats to animals is what you are looking for, you could do that with animals.addAll(cats).

Upvotes: 1

Related Questions