最近经常有一些项目须要给枚举设值一个int值,以及对int值进行反解析出枚举类型,代码以下:数组
1 public enum MatchResultEnum { 2 3 /** 4 * 赢 5 */ 6 WIN(0), 7 /** 8 * 输 9 */ 10 LOSE(1), 11 /** 12 * 平局 13 */ 14 DRAW(2); 15 16 /** 17 * 比赛结果的code值 18 */ 19 private int code; 20 21 MatchResultEnum(int value) { 22 this.code = value; 23 } 24 25 public int getCode() { 26 return code; 27 } 28 29 30 public static MatchResultEnum parse(int value) { 31 MatchResultEnum[] values = values(); 32 for (MatchResultEnum matchResult : values) { 33 if (matchResult.code == value) { 34 return matchResult; 35 } 36 } 37 return null; 38 } 39 }
后期优化以下:优化
1 private static MatchResultEnum[] result = {WIN, LOSE, DRAW}; 2 public static MatchResultEnum parse(int value) { 3 if (value < result.length) { 4 return result[value]; 5 } 6 return null; 7 } 8 9 //替换原代码:30-38行 ,缘由数组更加高效。可是这种用法有取巧的作法,前提是code值恰好是从0开始顺序递增的