Is there a best practice for writing maps literal style in Java?

前端 未结 9 1838
感情败类
感情败类 2020-12-24 03:03

In short, if you want to write a map of e.g. constants in Java, which in e.g. Python and Javascript you would write as a literal,

T CON         


        
9条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-24 03:45

    Constants? I'd use an enum.

    public enum Constants { 
        NAME_1("Value1"),
        NAME_2("Value2"),
        NAME_3("Value3");
    
        private String value;
    
        Constants(String value) {
            this.value = value;
        }
    
        public String value() {
            return value;
        }
    }
    

    Value for e.g. NAME_2 can be obtained as follows:

    String name2value = Constants.NAME_2.value();
    

    Only give the enum a bit more sensible name, e.g. Settings, Defaults, etc, whatever those name/value pairs actually represent.

提交回复
热议问题