Home > Blockchain >  ArrayList with unique classes
ArrayList with unique classes

Time:03-25

I have an Entity class, which has an ArrayList (called "effects") of subclasses of a class, StatusEffect. The ArrayList could have different subclasses of StatusEffect like Burning, Frozen, Nauseated. I also have a method, addEffect() which adds a subclass of status effect to the ArrayList using "effects.add(new SUBCLASS-NAME())". My question is how I could make it so that if the arrayList already has a SubClass of one type in it, it won't add the new effect. For example, if the ArrayList has the "Burning" class in it already, and I try to use addEffect(), it won't do anything because the ArrayList already has the class "Burning" in it.

What I tried was

protected void addEffect(StatusEffect effect) {
    if(!getEffects().contains(effect.getClass())) {
        effects.add(effect);
    }
    else {
        out.println(getName()   " was already affected by "   effect.getName());
    }
}

CodePudding user response:

If you want a single object per class in your data structure, you can use a Map. The key of the Map would be a Class representing the effect type and the value would be the concrete effect:

Map<Class<? extends StatusEffect>, StatusEffect> effects = new HashMap<>();

//insert only if not already there
effects.putIfAbsent(effect.getClass(), effect);
//insert or overwrite if already there
effects.put(effect.getClass(), effect);
//remove
effects.remove(effect.getClass());
//or
effects.remove(Burning.class);
//iterate
for(StatusEffect effect : effects.values()){
    //... 
}

The nature of Maps only allows a single value per key.

If you want to preserve order, you can use a LinkedHashMap instead of a HashMap.

  •  Tags:  
  • java
  • Related