Enum 相关,解决通过Key 获取 Value 或通过 value获取key

Enum 相关,enum通过Key 获取 Value 或通过 value获取key

本篇博客目的:解决通过Key 获取 Value 或通过 value获取key,以及工作中enum 类型的定义。

先解决问题:通过value 获取key,通过values() 方法获取此枚举的数组,遍历数组,通过key 获取value ,代码如下,参照下方原理解释在下方。

 public enum NationalityEnum {
    HAN("01","汉族");

    NationalityEnum(String code, String desc) {
        this.code = code;
        this.desc = desc;
    }

    private String code;
    private String desc;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    public static  String getCodeByDesc(String desc){
        NationalityEnum[] nationalityEnums = values();
        for (int i = 0; i < nationalityEnums.length; i++) {
            NationalityEnum nationalityEnum = nationalityEnums[i];
            if (nationalityEnum.getDesc().equals(desc)){
                return nationalityEnum.getCode();
            }
        }
        return null;
    }

    public static void main(String[] args) {
        String code = NationalityEnum.getCodeByDesc("汉族");
        System.out.println("code:"+ code);
    }
}

console输出:

"C:\Program Files\Java\jdk1.8.0_51\bin\java.exe" "-javaagent:
code:01

原理解释:key,value 相互获取的关键在于 enum value 方法,想点进去看一眼源码,不幸的是没有任何反应,咋办,最直接的方法就是阅读jdk 文档
jdk 文档地址

文档不长但是解决了问题
Java programming language enum types are much more powerful than their counterparts in other languages. The enum declaration defines a class (called an enum type). The enum class body can include methods and other fields. The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared. This method is commonly used in combination with the for-each construct to iterate over the values of an enum type. For example, this code from the Planet class example below iterates over all the planets in the solar system.

看见了没,对enum 提供values() 方法 ,并将enum声明成了数组,所以解决问题的方法就来了,遍历数组然后用用equals就可以实现key,values 的相互获取了


要克服生活的焦虑和沮丧,得先学会做自己的主人,有问题留言,没问题留下你的赞
博客声明:
1.博客内容全是对工作学习的总结
2.知识点都经过测试和推敲,如有疑问请留言,一定及时解决

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章