java 优雅地编写一个初始化的静态哈希表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7775919/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
writing an initialized static hashtable elegantly
提问by I J
Is there a way to write a static final Hashtable in java in key value pairs just like you can initialize a string array conveniently as :
有没有办法在Java中以键值对的形式编写静态最终Hashtable,就像您可以方便地初始化字符串数组一样:
String [] foo = {"A","AB"};
Basically what I mean is not having to write the words "put" for key:value pairs but instead may be something like:
基本上我的意思是不必为键:值对写“放置”这个词,而是可能是这样的:
Hashtable<String, String> foo = {"JJ":"222","KK":"222"}
which IMO looks more elegant.
IMO 看起来更优雅。
(I know the initialization would need to be in a static block. I am leaving that out for now)
(我知道初始化需要在一个静态块中。我现在不考虑了)
回答by brcosta
An anonymous inner class would give you double brace initialization, which is useful in some cases:
匿名内部类会给你双括号初始化,这在某些情况下很有用:
static final Map<String, String> map = new HashMap<String, String>() {{
put("foo", "bar");
put("x", "y");
}};
In any case, @michael667's answer is probably the best
无论如何,@michael667 的答案可能是最好的
回答by michael667
You can use guava's ImmutableMap:
您可以使用番石榴的ImmutableMap:
map = ImmutableMap.of(key1, value1, key2, value2);
These convenience methods exist for one to five elements. If you need more, you can use an ImmutableMap.Builder:
这些方便的方法适用于一到五个元素。如果需要更多,可以使用ImmutableMap.Builder:
static final ImmutableMap<String, Integer> WORD_TO_INT =
new ImmutableMap.Builder<String, Integer>()
.put("one", 1)
.put("two", 2)
.put("three", 3)
.build();
回答by rlibby
No, Java doesn't have map literals, but it does have array literals.
不,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]);
}
}
Of course this doesn't really add anything to the straightforward copy and paste put
solution, and it doesn't work well if your key and value types aren't the same.
当然,这并没有真正为简单的复制和粘贴put
解决方案添加任何东西,如果您的键和值类型不相同,它就不会很好地工作。
回答by Matthew Flaschen
No, you're looking for something like C#'s collection initializers, which doesn't currently exist in Java.
不,您正在寻找类似于 C# 的集合初始值设定项的东西,它目前在 Java 中不存在。
You can use an anonymous class to save a little typing, but you still have to write put
.
您可以使用匿名类来节省一点输入,但您仍然必须编写put
.