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.

问题评论:

    
You need only one list , not others.
    
Do I understand correctly, that you want to create Map<? extends Animal, List<? extends Animal>> without Reflection (i.e., looking at runtime for each implementation of Animal)?

原文地址:

https://stackoverflow.com/questions/47755921/java-how-do-you-make-one-arraylist-for-each-subclass

添加评论