JAVA的enum枚举数据类型的应用详解(持续ing)
enum是很雷同class了的,只是一种比较特殊的class类而已,JAVA对以enum类进行了特殊处理。
简单应用1:
public enum WeekDay{//定义一个WeekDay MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY//不需要带冒号 }
public class HelloWorld { public static void main(String[] args) { System.out.println(WeekDay.FRIDAY);//直接点,就可以点出来,并且作为离散值进行判断 } }
简单应用2:
enmu有属性
public enum WeekDay{ MONDAY(1,"MONDAY","星期一"), TUESDAY(2,"TUESDAY","星期二"), WEDNESDAY(3,"WEDNESDAY","星期三"), THURSDAY(4,"THURSDAY","星期四"), FRIDAY(5,"THURSDAY","星期五"), SATURDAY(6,"SATURDAY","星期六"), SUNDAY(7,"SUNDAY","星期天"); private int index;//数字索引 private String descEN;//英语名称 private String descCN;//汉语名称 private WeekDay(int index,String descEN,String descCN){//必须写这个构造函数,相当于初始化实例 this.index=index; this.descEN=descEN; this.descCN=descCN; } public String getDescCN(){//写一个get方法,获得汉语名称 return this.descCN; } }
public class HelloWorld { public static void main(String[] args) { System.out.println(WeekDay.FRIDAY);//直接点,就可以点出来,并且作为离散值进行判断 System.out.println(WeekDay.SATURDAY.getDescCN()); } }
常见用法3,一般是用来定义系统的错误标识
public enum ResultCodeEnum { SUCESS("0000","成功"), E9000("9000","缺少必要的字段"), E9001("9001","参数非法"), E9999("9999","系统内部异常,请联系管理员"); private String ResultCode; private String ResultDesc; private ResultCodeEnum(String ResultCode,String ResultDesc){ this.ResultCode = ResultCode; this.ResultCode = ResultDesc; } public String getResultDesc(){ return this.ResultDesc; } }