枚举普通使用
所有定义的枚举类型均继承至抽象类Enum,Enum的构造方法是私有化的,只有编译器可以调用。
package enumdemo;
import java.util.Arrays;
public class test {
public static void main(String[] args) {
Day day = Day.MONDAY;
System.out.println(day.name());
System.out.println(day.ordinal());
System.out.println(day.getClass());
System.out.println(day.toString());
System.out.println(Day.valueOf(Day.class,"MONDAY"));
Day[] days = Day.values();
System.out.println("days:" + Arrays.toString(days));
System.out.println(Day.values().length);
Enum e = Day.MONDAY;
Class<?> clazz = e.getDeclaringClass();
System.out.println(clazz);
/**
* 通过反射的方法获取enum实例
*/
Day[] dsz = (Day[]) clazz.getEnumConstants();
System.out.println(Arrays.toString(dsz));
}
public enum Day {
MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}
}
输出
MONDAY
0
class enumdemo.test$Day
MONDAY
MONDAY
days:[MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY]
7
class enumdemo.test$Day
[MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY]
枚举进阶应用
在枚举中定义变量或方法
package enumdemo;
public class Day2 {
public static void main(String[] args) {
for (Days day : Days.values()) {
// System.out.println(day+" "+day.desc+" "+day.getActivity());
System.out.println(day + " " + day.getDesc() + " " + day.getActivity());
}
}
public enum Days {
MONDAY("周一", "上班"),
TUESDAY("周二", "休息"),
WEDNESDAY("周三", "吃斋"),
THURSDAY("周四", "进修"),
FRIDAY("周五", "上班"),
SATURDAY("周六", "健身"),
SUNDAY("周日", "徒步");
public String desc;
private String activity;
/**
* 私有化构造函数,防止被外部调用
*
* @param desc
* @param activity
*/
Days(String desc, String activity) {
this.desc = desc;
this.activity = activity;
}
public String getDesc() {
return desc;
}
public String getActivity() {
return activity;
}
public Days getDay(String desc){
for(Days day : Days.values()){
if(day.desc.equals(desc)){
return day;
}
}
return null;
}
}
}
输出
MONDAY 周一 上班
TUESDAY 周二 休息
WEDNESDAY 周三 吃素
THURSDAY 周四 进修
FRIDAY 周五 上班
SATURDAY 周六 健身
SUNDAY 周日 徒步