Simple use of enumeration (get the value of the enumeration through the id of the enumeration or get the key of the enumeration through the value of the enumeration)

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);
    }

}

 

Guess you like

Origin blog.csdn.net/qq_36138652/article/details/109007989