Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

209
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda