Java:获取 ENUM 元素数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6160396/
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
Java: Getting an array of ENUM elements
提问by marcolopes
Is there a better way of creating arrays from elements of an enum:
有没有更好的方法从枚举的元素创建数组:
public static enum LOGICAL {
AND ("&", "AND"),
OR ("||", "OR");
public final String symbol;
public final String label;
LOGICAL(String symbol, String label) {
this.symbol=symbol;
this.label=label;
}
}
public static final String[] LOGICAL_NAMES = new String[LOGICAL.values().length];
static{
for(int i=0; i<LOGICAL.values().length; i++)
LOGICAL_NAMES[i]=LOGICAL.values()[i].symbol;
}
public static final String[] LOGICAL_LABELS = new String[LOGICAL.values().length];
static{
for(int i=0; i<LOGICAL.values().length; i++)
LOGICAL_LABELS[i]=LOGICAL.values()[i].label;
}
采纳答案by Bozho
No. That seems the proper way. Even if there was some utility, it would rely on reflection
不,这似乎是正确的方法。即使有一些效用,它也会依赖反射
If you are using it often cache it in the enum
如果您经常使用它,则将其缓存在枚举中
回答by Jon Skeet
Personally I wouldn't expose them as an array, whose contents can be changed by anyone. I'd probably use an unmodifiable list instead - and probablyexpose that via a property rather than as a field. The initialization would be something like this:
我个人不会将它们公开为数组,任何人都可以更改其内容。我可能会改用不可修改的列表 - 并且可能通过属性而不是字段来公开它。初始化将是这样的:
private static final List<String> labels;
private static final List<String> values;
static
{
List<String> mutableLabels = new ArrayList<String>();
List<String> mutableValues = new ArrayList<String>();
for (LOGICAL x : LOGICAL.values())
{
mutableLabels.add(x.label);
mutableValues.add(x.value);
}
labels = Collections.unmodifiableList(mutableLabels);
values = Collections.unmodifiableList(mutableValues);
}
(If you're already using Guavayou might even want to use ImmutableList
instead, and expose the collections that way to make it clear that they areimmutable.)
(如果您已经在使用Guava,您甚至可能想ImmutableList
改用它,并以这种方式公开集合以表明它们是不可变的。)
回答by AhmetB - Google
If you use your values very frequently and your enumeration gets bigger use Maps. Declare the following in your class.
如果您非常频繁地使用您的值并且您的枚举变得更大,请使用 Maps。在您的班级中声明以下内容。
private static EnumMap<LOGICAL,String> symbols = new EnumMap<LOGICAL, String>(LOGICAL.class);
and then just below it:
然后就在它下面:
static{
for(LOGICAL i : LOGICAL.values().)
symbols.put(i, i.symbol);
}
then you can use symbols.values()
or symbols.get(LOGICAL.AND)
etc.
然后你可以使用symbols.values()
或symbols.get(LOGICAL.AND)
等。