将枚举值与整数相关联

时间:2016-01-19 09:38:46

标签: java enums

我有这个枚举:

public enum Digits {
    ZERO(0);

private final int number;

    private Digits(int number) {
        this.number = number;
    }

    public int getValue(){
        return number;
    }
}

我想在另一个班级制作二传,我可以提供以下功能: - 我将给它整数值(在这种情况下为0),并且该setter将枚举ZERO设置为我的Digits类型的局部变量 那可能吗? 非常感谢!

3 个答案:

答案 0 :(得分:7)

有可能,但不能通过调用enum的构造函数,因为它只能在枚举本身中使用。

您可以在static中添加enum方法,该方法根据给定值检索正确的实例,例如ZERO如果给定的值为0

然后,在给出int参数时,您将在其他类中调用该方法。

自包含示例

public class Main {
    static enum Numbers {
        // various instances associated with integers or not
        ZERO(0),ONE(1),FORTY_TWO(42), DEFAULT;
        // int value
        private int value;
        // empty constructor for default value
        Numbers() {}
        // constructor with value
        Numbers(int value) {
            this.value = value;
        }
        // getter for value
        public int getValue() {
            return value;
        }
        // utility method to retrieve instance by int value
        public static Numbers forValue(int value) {
            // iterating values
            for (Numbers n: values()) {
                // matches argument
                if (n.getValue() == value) return n;
            }
            // no match, returning DEFAULT
            return DEFAULT;
        }
    }
    public static void main(String[] args) throws Exception {
        System.out.println(Numbers.forValue(42));
        System.out.println(Numbers.forValue(10));
    }
}

<强>输出

FORTY_TWO
DEFAULT

答案 1 :(得分:1)

你可以这样做:

private Digits digit;

public void setDigit(int number) {
    for (Digits value : Digits.values()) {
        if(value.getValue() == number) {
            digit = value;
        }
    }
}

答案 2 :(得分:1)

以下是如何实现您想要的实例

public enum Digit {

    ONE(1),
    TWO(2),
    THREE(3);

    private static final Map<Integer, Digit> mappingMap = new HashMap<Integer, Digit>();

    static {
        for (Digit m : Digit.values()) {
            mappingMap.put(m.getValue(), m);
        }
    }
    private final int digit;

    Digit(int aDigit) {
        digit = aDigit;
    }

    public int getValue() {
        return digit;
    }
    public static Digit getByDigit(int aDigit) {
        return mappingMap.get(aDigit);
    }
}

这种方法比迭代大型枚举的所有常量具有更好的性能。