如何在java中使用enumMap

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26357851/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 02:20:42  来源:igfitidea点击:

How to use enumMap in java

javaarraysenums

提问by Shadow

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.

你如何在java中使用enumMap?我想使用 enumMap 来获取从 0 到 n 的常量命名值,其中 n 是大小。但我不明白 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?

这不起作用。你应该如何使用 enumMap ?

is there also a way to do without x.put(Value.VALUE_ONE, 0);for every single element in the enum?

x.put(Value.VALUE_ONE, 0);对于枚举中的每个元素,还有没有办法做到这一点?

采纳答案by Justin

Don't attempt to store the size in the enumeration, EnumMaphas a sizemethod for that.

不要试图在枚举中存储大小,EnumMap有一个size方法。

public static enum Value{
    VALUE_ONE, VALUE_TWO
}

Also, enumeration types have a static method valuesthat you can use to get an array of the instances. You can use that to loop through and add them to the EnumMap

此外,枚举类型有一个静态方法values,您可以使用它来获取实例数组。您可以使用它来循环并将它们添加到 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 EnumMapotherwise you will have a NullPointerException:

您还需要确保初始化,EnumMap否则您将拥有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 EnumMapat all. That's only useful if you are trying to assign arbitrary values. You can get any enumeration by index using the valuesmethod:

如果您要做的只是通过索引检索枚举值,那么您根本不需要 an EnumMap。这仅在您尝试分配任意值时才有用。您可以使用以下values方法按索引获取任何枚举:

Value.values()[INDEX]

回答by SMA

You forgot to initialize EnumMap in your code.

您忘记在代码中初始化 EnumMap。

You could initialize it within main before x.put something like:

您可以在 x.put 之前在 main 中初始化它,例如:

x = new EnumMap<Value, Integer>(Value.class);

And use your array like:

并使用您的数组,如:

int[] myArray = new int[x.get(Value.SIZE)];

回答by JavaLearner

public static EnumMap<Value, Integer> x = new EnumMap<Value, Integer>(Value.class);