【问题标题】:Associate enum value to integer将枚举值与整数关联
【发布时间】:2016-04-24 17:10:50
【问题描述】:

我有这个枚举:

public enum Digits {
    ZERO(0);

private final int number;

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

    public int getValue(){
        return number;
    }
}

而且我想在另一个类中制作二传手,我可以提供以下功能: - 我将给它一个整数值(在本例中为 0),并且该设置器会将枚举零设置为我的数字类型的局部变量 那可能吗? 非常感谢!

【问题讨论】:

标签: java enums


【解决方案1】:

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

您可以做的是在您的 enum 中添加一个 static 方法,该方法根据给定值检索正确的实例,例如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

【讨论】:

  • 你能用Java写吗?
【解决方案2】:

你可以这样做:

private Digits digit;

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

【讨论】:

    【解决方案3】:

    这里是如何实现你想要的示例

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

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

    【讨论】:

      猜你喜欢
      • 2016-06-09
      • 2017-10-07
      • 1970-01-01
      • 2012-06-18
      • 1970-01-01
      • 1970-01-01
      • 2015-03-17
      • 1970-01-01
      相关资源
      最近更新 更多