首页 > 代码库 > JDK5-枚举

JDK5-枚举

1. 使用普通类模拟枚举

 1 public class Weekday {
 2     private Weekday() {} // 私有化
 3     
 4     public static final Weekday MONDAY = new Weekday();  // 每个枚举都是一个对象
 5     public static final Weekday TUESDAY = new Weekday();
 6 
 7     public String toString() {
 8         if(this == MONDAY)
 9             return "Monday";
10         else if(...) ...
11     }
12 }

 

2. 使用抽象类模拟枚举

 1 public abstract class Weekday {
 2     private Weekday() {}
 3 
 4     public final static Weekday MONDAY = new Weekday() {
 5         public Weekday nextDay() {
 6             return TUESDAY;
 7         }
 8     };
 9 
10     public final static Weekday TUESDAY = new Weekday() {
11         public Weekday nextDay() {
12             return WEDNESDAY;
13         }
14     };
15 
16     ...
17 
18     public abstract Weekday nextDay();
19 }

使用抽象类模拟可以免除写大量的if-else语句,不需要对每个对象进行判断,只需要有具体实现类完成即可

 

3. 枚举类

1 public enum Weekday {
2     SUN, MON, TUE, WED, THU, FRI, SAT
3 }

普通的枚举类末尾不需要写分号

 

4. 带构造参数枚举

1 public enum Weekday {    
2     SUN(5), MON(), TUE(7), WED(), THU(9), FRI, SAT;    // 必须第一行,且以分号结尾
3 
4     private Weekday() {}
5     private Weekday(int number) {
6         System.out.println(number);
7     }
8 }

枚举中每个变量都是static final的

 

5. 带抽象函数的枚举

 1 public enum Weekday {    // enum不用abstract修饰
 2     SUN(5) {
 3         public Weekday nextDay() {
 4             return MON;
 5         }
 6     }, 
 7     MON() {
 8         public Weekday nextDay() {
 9             return TUE;
10         }
11     }, 
12     TUE() {
13         public Weekday nextDay() {
14             return WED;
15         }
16     }, 
17     WED() {
18         public Weekday nextDay() {
19             return THU;
20         }
21     }, 
22     THU() {
23         public Weekday nextDay() {
24             return FRI;
25         }
26     }, 
27     FRI() {
28         public Weekday nextDay() {
29             return SAT;
30         }
31     }, 
32     SAT() {
33         public Weekday nextDay() {
34             return SUN;
35         }
36     };
37 
38     private Weekday() {}
39     private Weekday(int number) {
40         System.out.println(number);
41     }
42 
43     public abstract Weekday nextDay();
44 }

 

6. 枚举类中的方法

  toString()  - String

  name()  - String

  ordinal()  - int

  valueOf(String name)  - Weekday

  values()  - Weekday[]

 

JDK5-枚举