最近常常有一些项目需要给枚举设值一个int值,以及对int值进行反解析出枚举类型,代码如下:
1 public enumMatchResultEnum {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 intcode;20
21 MatchResultEnum(intvalue) {22 this.code =value;23 }24
25 public intgetCode() {26 returncode;27 }28
29
30 public static MatchResultEnum parse(intvalue) {31 MatchResultEnum[] values =values();32 for(MatchResultEnum matchResult : values) {33 if (matchResult.code ==value) {34 returnmatchResult;35 }36 }37 return null;38 }39 }
后期优化如下:
1 private static MatchResultEnum[] result ={WIN, LOSE, DRAW};2 public static MatchResultEnum parse(intvalue) {3 if (value
9 //替换原代码:30-38行 ,原因数组更加高效。但是这种用法有取巧的做法,前提是code值刚好是从0开始顺序递增的</