java Enum : 获取键列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2711862/
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
Enum : get the keys list
提问by Damien MATHIEU
I'm not a java developer. But I'm currently taking a look at Android applications development so I'm doing a bit of nostalgy, doing some java again after not touching it for three years.
我不是 Java 开发人员。但是我目前正在研究Android应用程序开发,所以我有点怀旧,在三年不接触它后再次做一些java。
I'm looking forward using the "google-api-translate-java" library.
In which there is a Languageclass. It's an enum allowing to provide the language name and to get it's value for Google Translate.
我期待使用“google-api-translate-java”库。
其中有一个语言类。它是一个枚举,允许提供语言名称并为谷歌翻译获取它的价值。
I can easily get all the values with :
我可以轻松获得所有值:
for (Language l : values()) {
// Here I loop on one value
}
But what I'd want to get is a list of all the keys names (FRENCH, ENGLISH, ...).
Is there something like a "keys()" method that'd allow me to loop through all the enum's keys ?
但我想要的是所有键名(法语、英语等)的列表。
是否有类似“keys()”方法可以让我遍历所有枚举的键?
回答by Jon Skeet
An alternative to Language.values()is to use EnumSet:
另一种方法Language.values()是使用EnumSet:
for (Language l : EnumSet.allOf(Language.class))
{
}
This is useful if you want to use it in an API which uses the collections interfaces instead of an array. (It also avoids creating the array to start with... but needs to perform other work instead, of course. It's all about trade-offs.)
如果您想在使用集合接口而不是数组的 API 中使用它,这很有用。(它也避免了从创建数组开始......但当然需要执行其他工作。这完全是权衡。)
In this particular case, values()is probably more appropriate - but it's worth at least knowing about EnumSet.
在这种特殊情况下,values()可能更合适 - 但至少值得了解EnumSet.
EDIT: Judging by another comment, you have a concern about toString()being overridden - call name()instead:
编辑:从另一条评论来看,您担心toString()被覆盖 -name()改为调用:
for (Language l : Language.values())
{
String name = l.name();
// Do stuff here
}
回答by b_erb
Try this:
试试这个:
for (Language l : Language.values()) {
l.name();
}
See also:
也可以看看:
回答by Little Bobby Tables
Yes - If the enum is X, use X.values(). See in this tutorial.
是 - 如果枚举是 X,则使用 X.values()。请参阅本教程。

