Heim  >  Fragen und Antworten  >  Hauptteil

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

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

高洛峰高洛峰2742 Tage vor555

Antworte allen(1)Ich werde antworten

  • 伊谢尔伦

    伊谢尔伦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);
        }
    }

    不知道是不是这个意思

    Antwort
    0
  • StornierenAntwort