Conveniently map between enum and int / String

前端 未结 18 1828
陌清茗
陌清茗 2020-11-28 01:07

When working with variables/parameters that can only take a finite number of values, I try to always use Java\'s enum, as in

public enum BonusT         


        
18条回答
  •  暖寄归人
    2020-11-28 01:17

    Both the .ordinal() and values()[i] are unstable since they are dependent to the order of enums. Thus if you change the order of enums or add/delete some your program would break.

    Here is a simple yet effective method to map between enum and int.

    public enum Action {
        ROTATE_RIGHT(0), ROTATE_LEFT(1), RIGHT(2), LEFT(3), UP(4), DOWN(5);
    
        public final int id;
        Action(int id) {
            this.id = id;
        }
    
        public static Action get(int id){
            for (Action a: Action.values()) {
                if (a.id == id)
                    return a;
            }
            throw new IllegalArgumentException("Invalid id");
        }
    }
    

    Applying it for strings shouldn't be difficult.

提交回复
热议问题