Q:

java - how do you make one ArrayList for each subclass?

I am trying to make an ArrayList that can be used by all subclasses of one abstract class, but the object types should be of the sublcasses.
To make it simple, here's an example:
There is an abstract class called 'Animal', and there are three subclasses called 'Dog', 'Cat', 'Pig'.
So, I want to make an 'ArrayList<Animal> all', and this list should be used by the subclasses to store the objects in their lists.
So, there must be an 'ArrayList<Dog>', 'ArrayList<Cat>' and 'ArrayList<Pig>' and so on.
I don't want to loop through the 'Animal' class, then convert each object cause that will make the non-inherited methods and values inaccessible...
I wanna do this so I can iterate through the objects faster.

A:

To give each subtype a list of its type, make Animal generic.
In Animal.java:
public class Animal<AnimalType extends Animal> {
    public List<AnimalType> getAll() {
        return all;
    }
    private List<AnimalType> all = new ArrayList<>();
}

In Dog.java:
public class Dog extends Animal<Dog> {
    public void doSomething() {
        for (Dog dog: getAll()) {
        }
    }
}

By making Animal "generic" you generally will want to refer to the specific type of animal you are dealing with. So, if you declare a variable to be of type Animal, you will want to include the type information (otherwise, you will get warnings about raw types). For example:
Animal<Dog> myFirstDog = ...;

If you want to refer to animals in general, then you might do this:
Animal<?> myFirstPet = ...;

If you make your animal hierarchy more interesting and also generic, then you might say something like:
Animal<? extends Canine> ...

which would might match Animal, Animal, or Animal.
In this last example:
In Canine.java:
public class Canine extends Animal<Canine> {
}

In Dog.java:
public class Dog extends Canine<Dog> {
}

In Coyote.java:
public class Coyote extends Canine<Coyote> {
}

