Enum :获取键列表
我期待使用“google-api-translate-java”库。
其中有 语言类。它是一个枚举,允许提供语言名称并获取它的 Google 翻译值。
我可以轻松获得所有值:
for (Language l : values()) {
// Here I loop on one value
}
但我想要获得的是所有键名称的列表(法语,英语,...)。
是否有类似“keys()”方法的东西可以让我循环遍历所有枚举的键?
I'm looking forward to using the "google-api-translate-java" library.
In which there is a Language class. It's an enum allowing to provide the language name and to get it's value for Google Translate.
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 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Language.values()
的替代方法是使用EnumSet
:如果您想在使用集合接口而不是数组的 API 中使用它,这非常有用。 (它还避免了创建数组来开始......但当然需要执行其他工作。这都是关于权衡的。)
在这种特殊情况下,
values()
可能更重要合适 - 但至少值得了解EnumSet
。编辑:从另一条评论来看,您担心
toString()
被覆盖 - 改为调用name()
:An alternative to
Language.values()
is to useEnumSet
: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.)
In this particular case,
values()
is probably more appropriate - but it's worth at least knowing aboutEnumSet
.EDIT: Judging by another comment, you have a concern about
toString()
being overridden - callname()
instead:试试这个:
另请参阅:
Try this:
See also:
是 - 如果枚举是 X,则使用 X.values()。请参阅本教程。
Yes - If the enum is X, use X.values(). See in this tutorial.