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.知識點都經過測試和推敲,如有疑問請留言,一定及時解決

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