Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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());
over 4 years ago · Santiago Trujillo Report

0

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());
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!