有没有办法在密钥值对中用java编写静态最终Hashtable,就像你可以方便地初始化字符串数组一样:
String [] foo = {"A","AB"};
Run Code Online (Sandbox Code Playgroud)
基本上我的意思是不必为键:值对写"put",而是可能是这样的:
Hashtable<String, String> foo = {"JJ":"222","KK":"222"}
Run Code Online (Sandbox Code Playgroud)
哪个IMO看起来更优雅.
(我知道初始化需要在一个静态块中.我现在暂时离开)
小智 10
匿名内部类将为您提供双括号初始化,这在某些情况下很有用:
static final Map<String, String> map = new HashMap<String, String>() {{
put("foo", "bar");
put("x", "y");
}};
Run Code Online (Sandbox Code Playgroud)
无论如何,@ michael667的答案可能是最好的
你可以使用guava的ImmutableMap:
map = ImmutableMap.of(key1, value1, key2, value2);
Run Code Online (Sandbox Code Playgroud)
不,Java没有地图文字,但它确实有数组文字.
static final Map<String, String> map;
static {
map = new HashMap<String, String>();
String[][] pairs = {
{"foo", "bar"},
{"x", "y"}
};
for (String[] pair : pairs) {
map.put(pair[0], pair[1]);
}
}
Run Code Online (Sandbox Code Playgroud)
当然,这并没有真正为简单的复制和粘贴put
解决方案添加任何内容,如果您的密钥和值类型不同,它也无法正常工作.
归档时间: |
|
查看次数: |
18491 次 |
最近记录: |