Frage

Correct me if I'm wrong:

  1. enum is a type
  2. an object of some enum type can take 1 and only 1 enum value at a time

Now I've got a question: Assume I've defined an enum(or some other data structure that's suitable for the task; I can't name it, because I'm looking for such a data structure to accomplish the following task) somewhere in my java program. If, somehow, I have an enum(or some other data structure) object in main(String []) and I want it to take multiple values of the enum(or some other data structure), how do I do it? What's the suitable data structure I should use if it's not enum?

Thanks in advance!

War es hilfreich?

Lösung

You could use a simple array, any collection from the core java.util API would also do the job (like lists or sets, it's a bit more convenient than using arrays), but probably what you are after is EnumSet:

enum Monster {
    GOBLIN, ORC, OGRE;
}

public class Main {
    public static void main(final String[] args) {
        final EnumSet<Monster> bigGuys = EnumSet.of(Monster.ORC, Monster.OGRE);

        for (final Monster act : Monster.values()) {
            System.out.println(bigGuys.contains(act));
        }
    }
}

Andere Tipps

Sounds like you are looking for either:

  • java.util.EnumSet
  • varargs: method(MyEnum ...values)
  • A simple array: MyEnum[]

I usually prefer the java.util.EnumSet myself, it's easy to work with and can quickly check if it contains a certain valaue etc. It's a subsitute for or of flags as well.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top