使用 Google 番石榴创建不可变版本后如何丢弃原始集合?

How to throw away the original collection once the Immutable version is created using Google Guava?

我有一张如下所示的地图,一旦我获得了原始地图的不可变版本,我就不再需要原始地图了。有没有办法让GC回收它?

Map<String, String> map = new TreeMap<>();
map.put("1", "one");
map.put("2", "two");
map.put("3", "three");

ImmutableMap<String, String> IMMUTABLE_MAP = ImmutableMap.copyOf(map);

您可以通过不再对 Map 进行任何引用来使其符合垃圾回收条件。当 map 超出范围时,这将自动发生。如果那是 "too late",您可以明确地将 null 分配给 map

无论哪种方式,实际的垃圾回收都是在 JVM 喜欢的时候在后台进行的。

另一个答案是正确的,但你应该尝试做的是使用

ImmutableMap<String, String> map =
         ImmutableMap.<String, String>builder()
    .put("1", "one")
    .put("2", "two")
    .put("3", "three")
    .build();

构建器针对其功能进行了优化,您通常可以将其全部写在一个表达式中。


更好的是

ImmutableMap<String, String> map = ImmutableMap.of(
    "1", "one",
    "2", "two",
    "3", "three");

最多适用于四个键值对。