Abd*_*aly 2 java collections guava
如果我想要一个空映射或一个元素映射,Java Collections有一个方法.为什么没有多个元素的方法?创建一个包含2个元素的静态最终地图的最佳方法是什么?我知道我可以这样做:
private static final Map<String, String> MAP = new HashMap<String, String>() {
{ put("a", "b"); put("c", "d"); }
};
Run Code Online (Sandbox Code Playgroud)
但是后来Eclipse抱怨serialVersionUID ......
Col*_*inD 16
原因Collections是0和1条目映射的方法是因为它们是特殊情况......例如,空Map是一个不可变的单例.
不过,对于你想做的事情,我强烈推荐使用番石榴.它的Immutable*系列(ImmutableMap具体)是你想要的我想的:
private static final ImmutableMap<String, String> MAP = ImmutableMap.of(
"a", "b",
"c", "d");
Run Code Online (Sandbox Code Playgroud)
您可以为小地图执行上述操作,对于较大的地图,您可以编写:
private static final ImmutableMap<String, String> MAP =
ImmutableMap.<String, String>builder()
.put("a", "b")
.put("b", "c")
...
.put("y", "z")
.build();
Run Code Online (Sandbox Code Playgroud)
如果您不使用Guava,您仍可能希望确保无法更改此地图.这很丑陋:
private static final Map<String, String> MAP;
static {
Map<String, String> temp = new HashMap<String, String>();
temp.put("a", "b");
temp.put("b", "c");
MAP = Collections.unmodifiableMap(temp);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
889 次 |
| 最近记录: |