2

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!

4

2 回答 2

7

您可以使用一个简单的数组,来自核心java.util API 的任何集合也可以完成这项工作(如列表或集合,它比使用数组更方便),但您所追求的可能是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));
        }
    }
}
于 2012-05-26T08:53:09.017 回答
2

听起来你正在寻找:

  • java.util.EnumSet
  • 可变参数:method(MyEnum ...values)
  • 一个简单的数组:MyEnum[]

我通常更喜欢java.util.EnumSet我自己,它易于使用并且可以快速检查它是否包含某个值等。它or也是标志的替代品。

于 2012-05-26T08:54:49.530 回答