在Java中编写地图文字样式是否有最佳实践?

简而言之,如果你想在Java中编写一个例如常量的映射,例如Python和Javascript,你会把它写成文字,

T CONSTANTS = { "CONSTANT_NAME_0": CONSTANT_VALUE_0 , "CONSTANT_NAME_1": CONSTANT_VALUE_1 , "CONSTANT_NAME_2": CONSTANT_VALUE_2 , //... } ; 

是否有一个Class或任何预设Object可用于编写这样的数据结构?

常数 ? 我会用枚举 。

 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值可以如下获得:

 String name2value = Constants.NAME_2.value(); 

只给枚举一个更明智的名称,例如SettingsDefaults等,无论这些名称/值对实际代表什么。

我喜欢这样做:

 Map map = new HashMap() {{ put("foo", "bar"); put(123, 456); }}; 

double {{}}是一个实例初始化块。 它们有点不寻常,但它们很有用。 不需要图书馆或帮助者。

不,Java没有地图文字。 您最接近的是使用Google Collections的ImmutableMap :

 Map CONSTANTS = ImmutableMap.of( NAME_1, VALUE_1, NAME_2, VALUE_2 //etc. ); 

对不起,我是一个修补匠:-)这是一个更清洁的方式。

 public class MapTest { private static Map map; static { Map tmpMap = new HashMap(); tmpMap.put("A", "Apple"); tmpMap.put("B", "Banana"); // etc map = Collections.unmodifiableMap(tmpMap); } public Map getMap() { return map; } } 

你可以自己编写一个快速帮助函数:

 @SuppressWarnings("unchecked") public static  Map ImmutableMap(Object... keyValPair){ Map map = new HashMap(); if(keyValPair.length % 2 != 0){ throw new IllegalArgumentException("Keys and values must be pairs."); } for(int i = 0; i < keyValPair.length; i += 2){ map.put((K) keyValPair[i], (V) keyValPair[i+1]); } return Collections.unmodifiableMap(map); } 

请注意,上面的代码不会阻止您覆盖同名的常量,使用CONST_1列表中的多个位置将导致最终的CONST_1值出现。

用法类似于:

 Map constants = ImmutableMap( "CONST_0", 1.0, "CONST_1", 2.0 ); 

这是另一种方式,最适合不会改变的地图:

 public class Whatever { private static Map map = new HashMap(); static { map.put("A", "Apple"); map.put("B", "Banana"); // etc } } 

Java7假设实现以下语法:

 Map = { "key1": "value", "key2": "value", "key3": "value", "key4": "value" }; 

但是现在你被迫使用Jorn或Tony Ennis提出的解决方案。

好吧,随着Jorn的改进,我似乎根本无法在内部或外部更改地图。 也许不那么可读,但如果你需要地图是不可修改的,我认为这更好。

 public class MapTest { private static Map map = initMap(); private static Map initMap() { Map map = new HashMap(); map.put("A", "Apple"); map.put("B", "Banana"); // etc return Collections.unmodifiableMap(map); } public Map getMap() { return map; } public static void main(String[] args) { MapTest m = new MapTest(); System.out.println(m.getMap().get("A")); m.getMap().put("this", "that"); } } 

我喜欢在同一行上进行声明和初始化。 我已经使用了这个方便的小实用程序这么长时间它基本上我的“地图文字”,直到他们在languange完成“正确”,我将继续使用它像那样:)

很高兴在这里分享。

 import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; /** * A handy utility for creating and initializing Maps in a single statement. * @author Jonathan Cobb. This source code is in the Public Domain. */ public class MapBuilder { /** * Most common create/init case. Usage: * * Map myPremadeMap = MapBuilder.build(new Object[][]{ * { "a", true }, { "b", false }, { "c", true }, { "d", true }, * { "e", "yes, still dangerous but at least it's not an anonymous class" } * }); * * If your keys and values are of the same type, it will even be typesafe: * Map someProperties = MapBuilder.build(new String[][]{ * {"propA", "valueA" }, { "propB", "valueB" } * }); * * @param values [x][2] array. items at [x][0] are keys and [x][1] are values. * @return a LinkedHashMap (to preserve order of declaration) with the "values" mappings */ public static  Map build(Object[][] values) { return build(new LinkedHashMap(), values); } /** * Usage: * Map myMap = MapBuilder.build(new MyMapClass(options), * new Object[][]{ {k,v}, {k,v}, ... }); * @param map add key/value pairs to this map * @return the map passed in, now containing new "values" mappings */ public static  Map build(Map map, Object[][] values) { for (Object[] value : values) { map.put((K) value[0], (V) value[1]); } return map; } /** Same as above, for single-value maps */ public static  Map build(Map map, K key, V value) { return build(map, new Object[][]{{key,value}}); } /** * Usage: * Map myMap = MapBuilder.build(MyMapClass.class, new Object[][]{ {k,v}, {k,v}, ... }); * @param mapClass a Class that implements Map * @return the map passed in, now containing new "values" mappings */ public static  Map build(Class> mapClass, Object[][] values) { final Map map; try { map = mapClass.newInstance(); } catch (Exception e) { throw new IllegalStateException("Couldn't create new instance of class: "+mapClass.getName(), e); } return build(map, values); } /** Usage: Map myMap = MapBuilder.build(key, value); */ public static  Map build(K key, V value) { Map map = new HashMap<>(); map.put(key, value); return map; } }