Java中枚举类Enum常见使用方法总结

方法一:

public enum Season {
    SPRING("spring","春天"),
    SUMMER("summer","夏天"),
    AUTUMN("autumn","秋天"),
    WINTER("winter","冬天");
    private String code;
    private String name;

    // 通过code获取name
    public static String getNameByCode(String code) {
        // 关于values(),可以理解为一个Map数组
        for (Season s : Season.values()) {
            if (code == s.getCode()) {
                return s.getName();
            }
        }
        return null;
    }
    // 构造方法
    Season (String code,String name) {
        this.code = code;
        this.name = name;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

测试用例一:

public class EnumDemo {
    public static void main (String args[]) {
        // 通过指定code,获取name
        String code = "spring";
        String name = Season.getNameByCode(code);
        System.out.println("通过code为spring获取的到name为:" + name);
        // 关于values(),可以理解为一个Map数组,
        // key是枚举对象,value有两个,一个是code,一个是name
        for (Season s : Season.values()) {
            System.out.println("");
            System.out.println("枚举对象:" + s);
            System.out.println("code:" + s.getCode());
            System.out.println("name:" + s.getName());
        }
    }
}

输出一:

在这里插入图片描述

方法二:重写toString()

public enum Job {
    DOCTOR("doctor","医生"),
    TEACHER("teacher","老师"),
    STUDENT("student","学生"),
    ENGINEER("engineer","工程师");
    private String code;
    private String name;

    Job(String code, String name) {
        this.code = code;
        this.name = name;
    }
    // POJO(Plain Ordinary Java Object)简单的Java对象,实际就是普通JavaBeans(类),
    // 一般来说具有一部分getter/setter方法的那种类就可以称作POJO。
    // 重写toString()方法后,更具体的表达对象属性
    // // toString()是Object类的方法,默认返回的是内存地址,就是一串hashcode
    @Override
    public String toString () {
        return "code=" + this.code +
                ",name=" + this.name;
    }
}

测试用例二:

public class EnumJob {
    public static void main (String args[]) {
        System.out.println(Job.DOCTOR.toString());
        System.out.println(Job.ENGINEER.toString());
        System.out.println(Job.STUDENT.toString());
        System.out.println(Job.ENGINEER.toString());
    }
}

输出二:

重写toString()方法前:
在这里插入图片描述
重写toString()方法后:
在这里插入图片描述

方法三:

参考博文:
https://blog.csdn.net/qq_27093465/article/details/52180865?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task

©️2020 CSDN 皮肤主题: 书香水墨 设计师:CSDN官方博客 返回首页