java 如何在arraylist中存储枚举的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32089114/
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
How to store value of enum in arraylist?
提问by ????
I have an enum
like this:
我有一个enum
这样的:
public enum SomeEnum
{
ENUM_VALUE1("Some value1"),
ENUM_VALUE2("Some value2"),
ENUM_VALUE3("Some value3");
}
I need to store values of enum
Some value1, Some value2and Some value3in an ArrayList
.
我需要将enum
Some value1、Some value2和Some value3 的值存储在ArrayList
.
I can get all values in an array using SomeEnum.values()
and iterate over that array and store the value in an ArrayList
like this:
我可以使用SomeEnum.values()
并迭代该数组来获取数组中的所有值,并将该值存储在ArrayList
这样的方式中:
SomeEnum values[] = SomeEnum.values();
ArrayList<SomeEnum> someEnumArrayList = new ArrayList<SomeEnum>();
for(SomeEnum value:values)
{
someEnumArrayList.add(value.getValue());
}
Is there any other method like values()
that returns array of Some value1, Some value2and Some value3?
有没有其他类似的方法values()
返回Some value1,Some value2和Some value3 的数组?
采纳答案by Tunaki
You could build that list inside the enum
itself like this:
您可以enum
像这样在自身内部构建该列表:
public enum SomeEnum {
ENUM_VALUE1("Some value1"),
ENUM_VALUE2("Some value2"),
ENUM_VALUE3("Some value3");
private static final List<String> VALUES;
private final String value;
static {
VALUES = new ArrayList<>();
for (SomeEnum someEnum : SomeEnum.values()) {
VALUES.add(someEnum.value);
}
}
private SomeEnum(String value) {
this.value = value;
}
public static List<String> getValues() {
return Collections.unmodifiableList(VALUES);
}
}
Then you can access this list with:
然后您可以通过以下方式访问此列表:
List<String> values = SomeEnum.getValues();
回答by Flown
If you're using Java 8 and cannot change the enum:
如果您使用的是 Java 8 并且无法更改枚举:
List<String> list = Stream.of(SomeEnum.values())
.map(SomeEnum::getValue)
.collect(Collectors.toList());
回答by pezetem
You can simply create list from array like this:
您可以简单地从数组创建列表,如下所示:
List<String> list = Arrays.asList(SomeEnum.values());