如何直接初始化一个HashMap(以字面的方式)? [英] How to directly initialize a HashMap (in a literal way)?
本文介绍了如何直接初始化一个HashMap(以字面的方式)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有一些方法可以初始化一个类似这样的Java HashMap:
Is there some way of initializing a Java HashMap like this?:
Map<String,String> test =
new HashMap<String, String>{"test":"test","test":"test"};
正确的语法是什么?我没有找到任何有关这一点。这可能吗?我正在寻找最短的/ fastet的方式,在一个地图中添加一些最终/静态值,从不改变,并在创建地图时提前知道。
What would be the correct syntax? I have not found anything regarding this. Is this possible? I am looking for the shortest/fastet way to put some "final/static" values in a map that never change and are known in advance when crerating the Map.
推荐答案
不,您必须手动添加所有元素。您可以使用静态初始化器:
No, you will have to add all the elements manually. You can use a static initializer though:
public class Demo
{
private static final Map<String, String> myMap;
static
{
myMap = new HashMap<String, String>();
myMap.put("a", "b");
myMap.put("c", "d");
}
}
这篇关于如何直接初始化一个HashMap(以字面的方式)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文