嗨,我想创建一个数组,其中每个位置都由一个枚举的值表示。
例如:
public enum type{
green,blue,black,gray;
}
现在我想创建一个数组,其中每个位置都是绿色,蓝色,...
我会更清楚的。我想创建一个数组,该数组中的位置由枚举类的值表示。而不是int [] array = new int [10] create int [] array = new int [type.value]
最佳答案
这是type[] allValues = type.values()
。参见this question。
或者,您可以使用 EnumSet
:
EnumSet<type> types = EnumSet.allOf(type.class);
这将为您提供高性能的
Set
实现,其中包含您的枚举值。PS:您应该以大写字母(CamelCase)开头的枚举类命名。
编辑:
似乎您想要的是Emum值的ordinal位置数组(为什么今天有人会使用Array而不是正确的Collection?):
type[] colors = type.values();
List<Integer> list = new ArrayList<Integer>(colors.length);
for (type color : colors) {
list.add(color.ordinal());
}
Integer[] array = list.toArray(new Integer[0]);
编辑2:也许您想使用带有
Map<Integer, type>
之类的键和值的0 => green, 1 => blue, 2 => black, 3=> gray
(问题尚不清楚)?