Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ArrayList with unique classes

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());
    }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading