Search code examples
javaenumsmultiple-value

Java Enum: Take Multiple Values at a Time


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!


Solution

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