Java Enum: Take Multiple Values at a Time

5.5k views Asked by At

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!

2

There are 2 answers

2
rlegendi On BEST ANSWER

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));
        }
    }
}
1
Mattias Isegran Bergander On

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.