Java基础系列:enum

1 Usage

1.0 遍历:values()

package com.company.basicdatatype;

enum Weekday{
     
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY,
    SUNDAY
}

public class EnumTest {
     

    public static void main(String[] args){
     
       
        for(Weekday s : Weekday.values()){
     
            System.out.println("Week:" + s);
        }
    }

}

1.2 取值valueOf(String)

package com.company.basicdatatype;

enum Weekday{
     
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY,
    SUNDAY
}

public class EnumTest {
     

    public static void main(String[] args){
     
        Weekday week = Weekday.FRIDAY;
        System.out.println("Week 1:" + week);
        System.out.println("===============");
        System.out.println("week 2:" + Weekday.MONDAY);
        System.out.println("===============");
        System.out.println("Week 3:" + Weekday.valueOf("MONDAY"));
        
    }

}

1.3 统一异常处理

package com.company.basicdatatype;

enum ResultEnum{
     
    SUCCESS(200, "成功"),
    NOT_FOUND(404, "未找到数据"),
    FAIL(201, "失败");

    private Integer code;
    private String message;

    ResultEnum(Integer code, String message){
     
        this.code = code;
        this.message = message;
    }

    public Integer getCode(){
     
        return code;
    }

    public String getMessage(){
     
        return message;
    }

}

public class EnumTest {
     

    public static void main(String[] args){
     
        System.out.println("Code:" + ResultEnum.SUCCESS.getCode());
        System.out.println("Message:" + ResultEnum.SUCCESS.getMessage());
    }

}

你可能感兴趣的:(#,Java,ABC,枚举,Java)