定义枚举的注意事项:
1 私有化构造器
2 用final修饰属性
3 只提供get方法
4 枚举类的实例需要在第一行列出,实例系统会自动添加 public static final 修饰
5 所有的枚举类都提供了一个 values 方法, 该方法可以很方便地遍历所有的枚举值
<span style="font-size:12px;">public enum WarnRankEnum{
//枚举类的实例,默认为public static final
RANK_RED(0,"暴雨红色警报"),
RANK_ORANGE(1,"暴雨橙色警报"),
RANK_YELLOW(2,"暴雨黄色警报"),
RANK_BLUE(3,"暴雨蓝色警报");
//final修饰属性
private final int rank;
private final String value;
//私有化构造函数
private WarnRankEnum(int rank,String value){
this.rank = rank;
this.value = value;
}
//只提供get方法
public int getRank() {
return rank;
}
public String getValue() {
return value;
}
//提供根据rank查询value的方法
public static String getValueById(int id){
switch(id){
case 0:
return RANK_RED.getValue();
case 1:
return RANK_ORANGE.getValue();
case 2:
return RANK_YELLOW.getValue();
default:
return RANK_BLUE.getValue();
}
}
}</span>