gpt4 book ai didi

java - Collections.unmodifyingMap 可以保留原始 map 吗?

转载 作者:行者123 更新时间:2023-12-01 07:55:53 25 4
gpt4 key购买 nike

我有下面一段代码:

class Util {
private static final Map<String, String> MY_MAP;

static {
Map<String, String> tmpMap = new TreeMap<String, String>();
tmpMap.put("key1", "val1");
tmpMap.put("key2", "val2");
tmpMap.put("key3", "val3");

MY_MAP = Collections.unmodifiableMap(tmpMap);
}

public static String getVal(String key) {
return MY_MAP.get(key);
}
}

MY_MAP可以一直保留tmpMap吗?或者换句话说,是否有可能GC会回收tmpMap从而导致MY_MAP无法访问?

最佳答案

返回的 Map 只是一个“ View ”,它包裹着传入的 Map。

所以,是的,只要 MY_MAP 还存在,tmpMap 就会被保留。由于 MY_MAP 是一个 static Final 字段,因此 tmpMap 将被保留 basically forever .

unmodifiableMap :

Returns an unmodifiable view of the specified map. [...] Query operations on the returned map "read through" to the specified map [...].

关于java - Collections.unmodifyingMap 可以保留原始 map 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30158482/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com