search

Home  >  Q&A  >  body text

java固定键值转换,使用枚举实现字典?

java,我想使用枚举实现int到string的转换,能做到吗?就如同字典一样。

高洛峰高洛峰2804 days ago595

reply all(1)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-18 10:56:56

    public enum MyDict {
        ChineseEnglish(0, "汉语词典"),
        EnglishChinese(1,"英汉词典"),
        EnglishEnglish(2,"英英词典");
        
        Integer id;
        String desc;
        
        MyDict(Integer id, String desc) {
            this.id = id;
            this.desc = desc;
        }
        
        static MyDict findById(Integer id) {
            MyDict dict;
            switch(id) {
            case 0:
                dict = MyDict.ChineseEnglish;
                break;
            case 1:
                dict = MyDict.EnglishChinese;
                break;
            case 2:
                dict = MyDict.EnglishEnglish;
                break;
            default:
                throw new IllegalArgumentException("非法ID");
            }
            return dict;
        }
        String getDesc() {
            return desc;
        }
        
        public static void main(String[] args) {
            String desc = MyDict.findById(0).getDesc();
            System.out.println(desc);
        }
    }

    I don’t know if that’s what it means

    reply
    0
  • Cancelreply