java - Accessing enum arguments outside of constructor? -
i'm having trouble trying fill static map values arguments of enum. example of i'm trying 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" , "numbertwo" map public static integer getnumbertwo(int numberone) { return numbers.get(numberone); } }
is there way access these variables in static block, or elsewhere outside of constructor? have been looking around while now, find nothing on it.
thanks in advance.
you need store numberone
, numbertwo
in enum
fields. can use static initialization block iterate values()
, store them in map
. 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 { (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); } }
Comments
Post a Comment