A more efficient way to using ArrayLists for a set of classes?

Viewed 62

I have a bunch of different enemy classes that move and behave differently, and often more than one instance of them is spawned on the screen as it's essentially all random, so I need to use an ArrayList so that I can control the behaviour of each individual enemy class.

But, this leaves me with a bunch of ArrayLists like this:

//Example:
ArrayList<Enemy1> enemies = new ArrayList<Enemy1>();
ArrayList<Enemy2> enemies = new ArrayList<Enemy2>();
ArrayList<Enemy3> enemies = new ArrayList<Enemy3>();
ArrayList<Enemy4> enemies = new ArrayList<Enemy4>();
ArrayList<Enemy5> enemies = new ArrayList<Enemy5>();

Is there any way to change the kind of data the ArrayList will store so that I can just empty and re-use different instances of the same ArrayList? Or anything, just so I don't have to have a billion ArrayLists in my code?

Additional info: I'm doing this using the Java Processing library, not sure if it changes anything.

Sorry if the answer is blatantly obvious to you, please don't be rude.

2 Answers

All your EnemyX classes must inherit from one interface or abstract class, then you can use a List<Enemy> that can hold any EnemyX object

Interface Enemy{}

Class Enemy1 implements Enemy{}
Class Enemy2 implements Enemy{}
Class Enemy3 implements Enemy{}

Use

List<Enemy> l = new ArrayList<>();
l.add(new Enemy1());
l.add(new Enemy2());
l.add(new Enemy3());

you can define an Enemy super class as (abstract or without abstract) with required methods and extend all other Enemy... classes from it and then access sub-classes from super-class:

public class Enemy { }

public abstract class Enemy { }

class Enemy1 extends Enemy { }
class Enemy2 extends Enemy { }
class Enemy3 extends Enemy { }
class Enemy4 extends Enemy { }

public static void main(String[] args) {
    List<Enemy> l = new ArrayList<>();
    l.add(new Enemy1());
    l.add(new Enemy2());
    l.add(new Enemy3());
}
Related