Java switch 中使用枚舉


問題

想使用switch去替換掉if-else,想到Hobby這個類里面的type屬性正好是個枚舉,就想用枚舉去實現,結果發現這樣是有問題的。

枚舉類

public enum HobbyEnum{
    SIGN("唱","SING"),
    JUMP("跳","JUMP"),
    RAP("Rap","RAP"),
    OTHER("未知","OTHER");
    
    private String word;
    private String type;
    
    HobbyEnum(String word, String type){
        this.word = word;
        this.type = type;
    }
    
    public String getWord() {
        return word;
    }

    public void setWord(String word) {
        this.word = word;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }
}

直接使用會報錯

解決方案

修改枚舉類

新增一個靜態方法,getByType()

enum HobbyEnum{
    SIGN("唱","SING"),
    JUMP("跳","JUMP"),
    RAP("Rap","RAP"),
    OTHER("未知","OTHER");

    private String word;
    private String type;

    HobbyEnum(String word, String type){
        this.word = word;
        this.type = type;
    }

    public String getWord() {
        return word;
    }

    public void setWord(String word) {
        this.word = word;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public static HobbyEnum getByType(String type){
        for (HobbyEnum constants : values()) {
            if (constants.getType().equalsIgnoreCase(type)) {
                return constants;
            }
        }
        return OTHER;
    }
}

修改實現邏輯

使用的時候直接根據type去獲取這個枚舉,這樣就可以進行判斷了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM