switch 结合 枚举使用

switch 结合枚举使用

一般枚举的格式是,枚举类.枚举类型,使用 switch 的要义在于,case 枚举类型,而不是 case 枚举类.枚举类型

定义一个枚举类
public enum TestEnum {
    TEST_ONE("name","one"),//枚举类型
    TEST_TWO("name","two");//枚举类型
    private String key;
    private String value;

    private TestEnum(String key,String value){
        this.key=key;
        this.value=value;
    }

    public String getKey() {
        return key;
    }
    public String getValue() {
        return value;
    }
}
switch 结合 枚举类型举例
public static void main(String[] args) {
        //声明一个枚举类型
        TestEnum t=TestEnum.TEST_ONE;

        //将枚举类型传入 switch 做为条件判断依据
        switch(t){
            case TEST_ONE://这里是关键点,TestEnum.TEST_ONE 只需写 TEST_ONE
                System.out.println("one");
                break;
            case TEST_TWO:
                System.out.println("two");
                break;
            default:
                break;
        }
    }
运行结果
one

猜你喜欢

转载自blog.csdn.net/bestcxx/article/details/80292884