java enum ArrayList - 这可能吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6975542/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 18:06:34  来源:igfitidea点击:

java enum ArrayList - is this possible?

javaenums

提问by CodeGuy

Possible Duplicate:
Adding enum type to a list

可能的重复:
将枚举类型添加到列表

I have an enum class:

我有一个枚举类:

public enum MyEnum {
    ONE, TWO, THREE;
}

And in another class, MyClass.java, I want to have the following

在另一个类 MyClass.java 中,我想要以下内容

ArrayList<MyEnum> list;

is this possible? because I'm encountering some issues.

这可能吗?因为我遇到了一些问题。

回答by MByD

There should be no problem doing that.

这样做应该没有问题。

This code compiles fine:

这段代码编译得很好:

package example; 

import java.util.ArrayList;
import java.util.List;

public class Example {

    public static void main (String[] args) {
        List<MyEnum> enums = new ArrayList<MyEnum>();
    }

    enum MyEnum { ONE, TWO, THREE;}
    //         no need for that  ^ but added to match your question
}

回答by Tomasz Nurkiewicz

Despite "some issues" you have, aren't you actually looking for an EnumSet?

尽管您有“一些问题”,但您实际上不是在寻找EnumSet吗?

EnumSet<MyEnum> set = EnumSet.of(MyEnum.ONE, MyEnum.THREE);