将枚举值与整数相关联

use*_*755 6 java enums

我有这个枚举:

public enum Digits {
    ZERO(0);

private final int number;

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

    public int getValue(){
        return number;
    }
}
Run Code Online (Sandbox Code Playgroud)

我想在另一个类中创建setter,我可以提供以下功能: - 我将给它整数值(在这种情况下为0),并且setter将枚举ZERO设置为我的本地变量Digits是可能的吗?非常感谢!

Men*_*ena 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));
    }
}
Run Code Online (Sandbox Code Playgroud)

产量

FORTY_TWO
DEFAULT
Run Code Online (Sandbox Code Playgroud)