问题描述
如何在java中使用enumMap?我想使用枚举地图来获取从0到n的常量命名值,其中n是大小。但我不明白oracle网站上的描述> 。我试图在这里使用一个
package myPackage;
import java.util.EnumMap;
public class Main {
public static枚举值{
VALUE_ONE,VALUE_TWO,SIZE
}
public static EnumMap< ;值,整数> X;
public static void main(String [] args){
x.put(Value.VALUE_ONE,0);
x.put(Value.VALUE_TWO,1);
x.put(Value.SIZE,2);
int [] myArray = new int [SIZE];
}
}
工作你应该如何使用枚举地图?
还有一种方法可以不使用 x.put(Value.VALUE_ONE,0);
枚举中的每一个元素?
不要尝试将大小存储在枚举中, EnumMap
有一个大小
方法。
public static枚举值{
VALUE_ONE,VALUE_TWO
}
此外,枚举类型具有静态方法值
,可用于获取实例数组。你可以使用它来循环并将它们添加到EnumMap
public static void main(String [] args){$ b (int i = 0; i< Value.values()。length; i ++){
x.put(Value.values()[i],i);
}
int [] myArray = new int [x.size()];
}
您还需要确保初始化 EnumMap
否则你将有一个 NullPointerException
:
public static EnumMap< Value,Integer> x = new EnumMap<>(Value.class);
如果您想要做的是通过索引检索枚举值,那么您不需要枚举地图。这只有在您尝试分配任意值时才有用。
您可以使用值获取索引的任何枚举方法:
Value.values()[INDEX]
How do you use enumMap in java? I want to use an enumMap to get constant named values that go from 0 to n where n is size. But I don't understand the description on the oracle site > EnumMap.
I tried to use one here
package myPackage;
import java.util.EnumMap;
public class Main{
public static enum Value{
VALUE_ONE, VALUE_TWO, SIZE
}
public static EnumMap<Value, Integer> x;
public static void main(String[] args){
x.put(Value.VALUE_ONE, 0);
x.put(Value.VALUE_TWO, 1);
x.put(Value.SIZE, 2);
int[] myArray = new int[SIZE];
}
}
This doesn't work. How are you supposed to use an enumMap?
is there also a way to do without x.put(Value.VALUE_ONE, 0);
for every single element in the enum?
Don't attempt to store the size in the enumeration, EnumMap
has a size
method for that.
public static enum Value{
VALUE_ONE, VALUE_TWO
}
Also, enumeration types have a static method values
that you can use to get an array of the instances. You can use that to loop through and add them to the EnumMap
public static void main(String[] args){
for(int i = 0; i < Value.values().length ; i++) {
x.put(Value.values()[i], i);
}
int[] myArray = new int[x.size()];
}
You also need to be sure to initialize the EnumMap
otherwise you will have a NullPointerException
:
public static EnumMap<Value, Integer> x = new EnumMap<>(Value.class);
If all you're trying to do is retrieve enumeration values by indices then you don't need an EnumMap
at all. That's only useful if you are trying to assign arbitrary values.You can get any enumeration by index using the values
method:
Value.values()[INDEX]
这篇关于如何在java中使用enumMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!