Java中的枚举(enum)
枚举的使用:
//枚举 enum Weekday { SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY; } public class helloworld { public static void main(String[] args) { System.out.println(Weekday.SUNDAY);//打印出SUNDAY,因为父类Enumo重写了toString方法 Weekday[] days = Weekday.values(); for(Weekday d : days) { System.out.println(d); } Weekday day = Weekday.valueOf("SATURDAY"); switch(day) { case SUNDAY: case SATURDAY: System.out.println("周末"); break; default: System.out.println("周一~周五"); break; } } }
Weekday用Xjad反编译后为
final class Weekday extends Enum { public static final Weekday SUNDAY; public static final Weekday MONDAY; public static final Weekday TUESDAY; public static final Weekday WEDNESDAY; public static final Weekday THURSDAY; public static final Weekday FRIDAY; public static final Weekday SATURDAY; private static final Weekday $VALUES[]; public static Weekday[] values() { return (Weekday[])$VALUES.clone(); } public static Weekday valueOf(String s) { return (Weekday)Enum.valueOf(Weekday, s); } private Weekday(String s, int i) { super(s, i); } static { SUNDAY = new Weekday("SUNDAY", 0); MONDAY = new Weekday("MONDAY", 1); TUESDAY = new Weekday("TUESDAY", 2); WEDNESDAY = new Weekday("WEDNESDAY", 3); THURSDAY = new Weekday("THURSDAY", 4); FRIDAY = new Weekday("FRIDAY", 5); SATURDAY = new Weekday("SATURDAY", 6); $VALUES = (new Weekday[] { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }); } }
switch的一段,反编译为
switch (1..SwitchMap.Weekday[weekday.ordinal()]) { case 1: // '\001' case 2: // '\002' System.out.println("周末"); break; default: System.out.println("周一~周五"); break; }
可以认为,所有的enum的父类都是Enum类,Enum含有的方法
protected Enum(String name, int ordinal) 唯一的构造函数。 String name() 返回此枚举常量的名称,与其枚举声明中声明的完全相同。 int ordinal() 返回此枚举常数的序数(其枚举声明中的位置,其中初始常数的序数为零)。 String toString() 返回声明中包含的此枚举常量的名称。 boolean equals(Object other) 如果指定的对象等于此枚举常量,则返回true。
******************
常记溪亭日暮,沉醉不知归路。兴尽晚回舟,误入藕花深处。争渡,争渡,惊起一滩鸥鹭。
昨夜雨疏风骤,浓睡不消残酒。试问卷帘人,却道海棠依旧。知否?知否?应是绿肥红瘦。