gpt4 book ai didi

java - 创建一个数组,其中每个位置都是枚举类型

转载 作者:搜寻专家 更新时间:2023-10-31 19:41:11 27 4
gpt4 key购买 nike

您好,我想创建一个数组,其中每个位置都由枚举值表示。

例如:

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)开头命名枚举类。

编辑:

似乎你想要 ordinal 的数组你的 emum 值的位置(为什么现在有人会使用数组而不是正确的集合?):

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]);

EDIT2:也许你想要 Map<Integer, type>使用键和值,如 0 => green, 1 => blue, 2 => black, 3=> gray (问题还不清楚)?

关于java - 创建一个数组,其中每个位置都是枚举类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8468078/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com