在Java中编写地图字面风格有最佳实践吗? [英] Is there a best practice for writing maps literal style in Java?
问题描述
总之,如果你想写一个例如。 Java中的常量。 Python和Javascript你会写成一个文字,
T< String,String> CONSTANTS =
{
{
CONSTANT_NAME_0:CONSTANT_VALUE_0,
CONSTANT_NAME_1:CONSTANT_VALUE_1,
CONSTANT_NAME_2:CONSTANT_VALUE_2,
// ...
};
有 Class
code> code> Object 常量?我将使用枚举。
public enum常数{
NAME_1(Value1),
NAME_2(Value2),
NAME_3(Value3);
private String value;
常量(字符串值){
this.value = value;
}
public String value(){
return value;
}
}
NAME_2
可以获得如下:
字符串name2value = Constants.NAME_2 。值();
只给予枚举一个更明智的名称,例如 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, is there a Constants? I'd use an enum. Value for e.g. Only give the enum a bit more sensible name, e.g. 这篇关于在Java中编写地图字面风格有最佳实践吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!设置
,默认
等,无论这些名称/值对 p> T<String,String> CONSTANTS =
{
"CONSTANT_NAME_0": CONSTANT_VALUE_0 ,
"CONSTANT_NAME_1": CONSTANT_VALUE_1 ,
"CONSTANT_NAME_2": CONSTANT_VALUE_2 ,
//...
} ;
Class
or any preset Object
that you can use for writing a data structure like that?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;
}
}
NAME_2
can be obtained as follows:String name2value = Constants.NAME_2.value();
Settings
, Defaults
, etc, whatever those name/value pairs actually represent.