Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

210
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda