JAVA在声明HashMap时初始化它



我目前正在使用一个预填充的Hashmap,但我无法想出一种有效的方法来立即声明Hashmap。我可以做的一种方法是:

static final LinkedHashMap<String, Integer> test = new LinkedHashMap<String, Integer>() {{
}}

但有人告诉我,由于运行时间等原因,这种方式并不好。。不过,我需要一种方法,立即填充List,而不是在方法中,因为我需要它的方法被多次访问。

使用Java 9+中的java.util.Map#of()

static final Map<String, Integer> map = Map.of(
"key1", 42,
"key2", 69
);

如果你特别想要一个HashMap,就用它作为包装器:new HashMap(Map.of(...))

你总是可以这样做:

static LinkedHashMap<String, Integer> test;
static {
test = new LinkedHashMap<String, Integer>()
test.put("key", 1);
//etc
}

如果你需要它是最终的,那么内联初始化它,并在静态块中填充数据;

您可以有一个加载地图的方法

static final Map<String, Integer> TEST = loadTest();
private static Map<String, Integer> loadTest() {
Map<String, Integer> ret = new LinkedHashMap<>();
// populate the map.
return ret;
}

延迟加载数据的另一种方法

static final Map<String, Integer> TEST = new LinkedHashMap<>();
static Integer getTest(String key) {
return TEST.computeIfAbsent(key, k -> valueForKey(k));
}
static int valueForKey(String key) {
// load one value, only called once per key
}

,而不是在方法中,因为我需要它的方法被多次访问。

这是一种误解。

static final LinkedHashMap singleton = createMap();
//called once.
private static LinkedHashMap<K,V> createMap(){
//create and return map.
}
public LinkedHashMap<K, V> getMap(){
return new LinkedHashMap<>(singleton);
}

创建代码被调用一次,映射被访问多次。

最新更新