枚举的简单使用(通过枚举的id获取枚举的值或者通过枚举的值获取枚举的key)

public enum EnumTest {
    CHINA(1,"中国"),
    KONGHONG(2,"香港");
    private Integer id;
    private String countryName;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getCountryName() {
        return countryName;
    }

    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }

    private EnumTest(Integer id, String countryName) {
        this.id = id;
        this.countryName = countryName;
    }

    public static String getCountryValue(Integer id) {
        EnumTest[] carTypeEnums = values();
        for (EnumTest enumTest : carTypeEnums) {
            if (enumTest.id == id) {
                return enumTest.getCountryName();
            }
        }
        return null;
    }

    public static Integer getId(String countryName) {
        EnumTest[] carTypeEnums = values();
        for (EnumTest enumTest : carTypeEnums) {
            if (enumTest.countryName.equals(countryName)) {
                return enumTest.getId();
            }
        }
        return null;
    }

    public static void main(String[] args) {
        String name = EnumTest.getCountryValue(1);
        Integer id = EnumTest.getId("香港");
        System.out.println(name);
        System.out.println(id);
    }

}

猜你喜欢

转载自blog.csdn.net/qq_36138652/article/details/109007989