網頁

2017/10/17

Java 列舉(Enum)範例

Java 列舉(Enum)範例

public enum WeekDay {
  
    SUN("Sunday","星期日"),
    MON("Monday","星期一"),
    TUE("Tuesday","星期二"),
    WED("Wednesday","星期三"),
    THU("Thursday","星期四"),
    FRI("Friday","星期五"),
    SAT("Saturday","星期六");

    WeekDay(String day, String chinese){
        this.day = day;
        this.chinese = chinese;
    }

    private final String day;
    private final String chinese;

    public static WeekDay getWeek(int i){

        switch(i){
            case 0: return SUN;
            case 1: return MON;
            case 2: return TUE;
            case 3: return WED;
            case 4: return THU;
            case 5: return FRI;
            case 6: return SAT;
            default: return null;
        }

    }

    public String getDay(){
        return this.day;
    }

    public String getChinese(){
        return this.chinese;
    }

}

測試

public class Main {

    public static void main(String[] args) {
    
        WeekDay weekDay = WeekDay.getWeek(0);
        System.out.println(weekDay.getDay());
        System.out.println(weekDay.getChinese());
    
    }
  
}

執行後印出如下

Sunday
星期日

原本取得WeekDay的靜態方法getWeek()中,是透過switch case依傳入的參數來選擇對應的WeekDay,下面範例進一步把switch case消除。

public enum WeekDay {

    SUN("Sunday","星期日", 0),
    MON("Monday","星期一", 1),
    TUE("Tuesday","星期二", 2),
    WED("Wednesday","星期三", 3),
    THU("Thursday","星期四", 4), 
    FRI("Friday","星期五", 5),
    SAT("Saturday","星期六", 6);

    WeekDay(String day, String chinese, int code){
        this.day = day;
        this.chinese = chinese;
        this.code = code;
    }

    private final String day;
    private final String chinese;
    private int code;

    public static WeekDay getWeek(int i){
        for(WeekDay weekDay : values()){
            if(weekDay.getCode() == i) {
                return weekDay;
            }
        }
        return null;
    }

    public String getDay(){
        return this.day;
    }
    
    public String getChinese() {
        return this.chinese;
    }

    public int getCode() {
        return this.code;
    }
  
}

在上面的WeekDay新增了一個屬性code及其getter,然後使用Enum本身的values()方法可取得裝有列舉(星期一到星期日)的陣列,這樣便可以利用for迴圈與傳入的參數比對,數字相同則回傳該筆列舉。

注意Enum的values()方法是由compiler提供,所以沒有Java Doc文件。values()是靜態方法,呼叫後會回傳列舉中全部的值所組成的陣列,例如WeedDay.values()的內容是

[SUN, MON, TUE, WED, THU, FRI, SAT]

如果文章有幫助還幫忙點個Google廣告,感恩。

2 則留言:

  1. 請問裡面的 switch case 是不是要加上 break 呢?

    回覆刪除
  2. @Jimmy 不用喔,因為直接return了,不會往下走。

    回覆刪除