John Harlan
John Harlan

Reputation: 123

Java list/array of animals containing a variety of animals

I need a list of all the animals. I have a basic Animal class and would like to extend it to dogs, cats, iguanas, etc.

Is there a good way to get them all into one List?

I want to be able to check the entire list of all animals without having to change all the previously made animals. They should know about all the other Animal classes made after them.

Upvotes: 3

Views: 4619

Answers (4)

Sina Madani
Sina Madani

Reputation: 1324

You can use List<? extends Animal> animals = new ArrayList<>(); and then add any type of animal to the list.

Upvotes: 1

Blake Yarbrough
Blake Yarbrough

Reputation: 2316

You can make any number of Animals by extending an Animal base class like this:

public class Dog extends Animal {

}

Then you can declare a new list of animals.

List<Animal> animals = new ArrayList<Animal>();

Once you have done that, you can add any number of new objects the extend the Animal class to your list.

animals.add(new Dog());
animals.add(new Cat());
animals.add(new Iguana());

Upvotes: 3

slartidan
slartidan

Reputation: 21608

You can create a List<Animal> like this:

// create empty list
List<Animal> animals = new ArrayList<>();

// add any kind of animal
animals.add(new Kangaroo());
animals.add(new Butterfly());

// use that list later
int numberOfAnimals = animals.size();
for (Animal animal : animals) {
    // do something
}

Things to keep in mind:

  • when using items of the animal list you do not know anymore which kind of animal it is. If you want to access Kangaroo-specific details of an animal you should check, whether the item actually is a Kangaroo (using instanceof)
  • You can only add objects to the list of animals, whose class extends Animal.
  • In general it is a good idea to keep your code as general as posible. If you need special features of an ArrayList, then make your animals an ArrayList. But in most cases defining the variable as List or even Collection (or Iterable) makes your code more flexible.

Upvotes: 3

Geralt_Encore
Geralt_Encore

Reputation: 3771

It is called Polymorphism. So basically, you answered to your question by yourself. It is perfectly legal in Java to add to collection objects of subtypes of declared collection's type.

Upvotes: 1

Related Questions