将地图分配给ImmutableMap之后,如何停止或限制重新分配其他地图

问题描述 投票:1回答:2

我宣告了类似的ImmutableMap

public static ImmutableMap<String, String> mapImmutable;

将映射分配给该变量

mapImmutable= ImmutableMap.copyOf(map2);

现在,如果我将其他地图分配给此“ mapImmutable”变量。它不会引发任何异常,并且会更新值。

mapImmutable=ImmutableMap.copyOf(map3);

公共类UnmodifiedMap {

public static ImmutableMap<String, String> mapImmutable;

public static void main(String[] args) {
    Map<String,String> map2=new HashMap<String,String>();

    map2.put("name", "mark");
    mapImmutable= ImmutableMap.copyOf(map2);
    System.out.println(mapImmutable);

    Map<String,String> map3=new HashMap<String,String>();

    map3.put("Country", "USA");
    map3.put("name", "Joy");

            mapImmutable=ImmutableMap.copyOf(map3);\\It should throw an exception while reassign.
    System.out.println(mapImmutable);}}

控制台结果-:{name = mark}{Country = USA}

重新分配时应该抛出异常。

java collections guava immutability
2个回答
1
投票

您应该区分Map的不变性和mapImmutable字段的不变性。


0
投票

这里:

© www.soinside.com 2019 - 2024. All rights reserved.