zoukankan      html  css  js  c++  java
  • Java switch 中如何使用枚举?

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

    想使用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;
    }
    }

    转载至 https://www.cnblogs.com/codeclock/p/12564924.html

    假如我的博客对你有用,请你关注我一下,告诉我你来过,你的关注是我前进的动力,希望更多的人记录自己的问题,去帮助别人更是帮助自己避免再次出现这样那样的问题,谢谢你的来过!
  • 相关阅读:
    【bzoj2561】最小生成树 网络流最小割
    【bzoj4407】于神之怒加强版 莫比乌斯反演+线性筛
    【bzoj4816】[Sdoi2017]数字表格 莫比乌斯反演
    【bzoj3252】攻略 贪心+DFS序+线段树
    【bzoj1690】[Usaco2007 Dec]奶牛的旅行 分数规划+Spfa
    【bzoj3291】Alice与能源计划 模拟费用流+二分图最大匹配
    【bzoj2752】[HAOI2012]高速公路(road) 线段树
    wpf--- TextBlock文字设置属性
    无边框WPF窗体——允许拖动
    C# 枚举、字符串、值的相互转换
  • 原文地址:https://www.cnblogs.com/zxy-come-on/p/15131504.html
Copyright © 2011-2022 走看看