Accessing enum arguments outside of constructor?

I'm having trouble trying to fill a static map with values from arguments of an enum. Example of what I'm trying to say here:

public enum LettersAndNumbers {
     A(1, 2),
     B(2, 3);

     private static HashMap<Integer, Integer> numbers = new HashMap<Integer, Integer();

     private LettersAndNumbers(int numberone, int numbertwo) {}

      // Somehow put arguments "numberone" and "numbertwo" into map

     public static Integer getNumberTwo(int numberone) {
          return numbers.get(numberone);
     }
}

Is there a way to access these variables in a static block, or elsewhere outside of the constructor? I have been looking around for a while now, but I could find nothing on it.

Thanks in advance.


You need to store the numberone and numbertwo in your enum as fields. Then you can use a static initialization block to iterate the values() and store them in your Map . Something like,

public enum LettersAndNumbers {
    A(1, 2), B(2, 3);
    private int numberone;
    private int numbertwo;
    private static Map<Integer, Integer> numbers = new HashMap<>();
    static {
        for (LettersAndNumbers lan : LettersAndNumbers.values()) {
            numbers.put(lan.numberone, lan.numbertwo);
        }
    }

    private LettersAndNumbers(int numberone, int numbertwo) {
        this.numberone = numberone;
        this.numbertwo = numbertwo;
    }

    public static Integer getNumberTwo(int numberone) {
        return numbers.get(numberone);
    }
}
链接地址: http://www.djcxy.com/p/38076.html

上一篇: 封闭类中的私有枚举和静态字段

下一篇: 在构造函数之外访问枚举参数?