天天看點

Enum枚舉類詳解

enum Day {

MONDAY, TUESDAY, WEDNESDAY

}

枚舉類通過enum關鍵字修飾,枚舉類不能繼承其他類,可以實作接口,原理是枚舉類預設繼承Enum,編譯後的結果是

final class Day extends java.lang.Enum<Day>

Enum枚舉類詳解
public enum SortType {

    ASC("ASC"),DESC("DESC");

    private String value;

    /**
    * @param value 值
    */
    SortType(String value) {
        this.value = value;
    }
    /**
    * @return 值
    */
    public String getValue() {
        return this.value;
    }
}
           
SortType.DESC.getValue()
           

這是我們代碼中常用枚舉類的一種方式;

相當于一個常量類,也可以把枚舉類當作是一個字典類,如下:

public enum FlightType { 
    OW(1, "單程"), RT(2, "往返"); 

    public Integer code; 
    public String desc; 
    FlightType(Integer code, String desc) { 
        this.code = code; 
        this.desc = desc; 
    } 
    public Integer getCode() {
        return code;
    } 
    public void setCode(Integer code) {
        this.code = code;
    } 
    public String getDesc() {
        return desc;
    } 
    public void setDesc(String desc) {
        this.desc = desc;
    } 
    public static FlightType getTypeByCode(Integer code) { 
        if (code != null) {
            for (FlightType ftype : FlightType.values()) { 
                if (ftype.code == code) { 
                    return ftype; 
                } 
            } 
        }
        return null;
    } 

    public static String getDescByCode(Integer code) { 
        return getTypeByCode(code).desc; 
    } 
}
           
下一篇: 枚舉 enum