将Map分配给ImmutableMap后,如何停止或限制重新分配另一个地图

After assigning a Map to ImmutableMap, how to stop or restrict reassign another map

我像这样声明了一个 ImmutableMap

public static ImmutableMap<String, String> mapImmutable;

为这个变量分配了一个映射

mapImmutable= ImmutableMap.copyOf(map2);

现在,如果我将其他地图分配给此 'mapImmutable' 变量。它不会抛出任何异常并会更新值。

mapImmutable=ImmutableMap.copyOf(map3);

public class 未修改地图 {

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);}}

控制台结果-: {名称=标记} {国家=美国}

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

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

顾名思义,ImmutableMap是不可变的,但是在您的代码中,指向地图的字段只是一个常规字段。因此,它可以重新分配以指向不同的地图。如果您希望该字段不可变,只需将其标记为 final.

这里:

mapImmutable = ImmutableMap.copyOf(map3);

您实际上并未更改字段 mapImmutable 所指的地图内容。您正在使 mapImmutable 引用完全不同的地图!

ImmutableMap 不可变并不意味着您可以重置其类型的变量。它只意味着它的实例不会改变。例如您不能向地图添加新项目或从中删除项目。在上面的行中,您没有修改 ImmutableMap 的任何实例,而是通过调用 copyOf 创建 ImmutableMapnew 实例,并赋值它到 mapImmutablemapImmutable 所指的地图没有改变,只是 丢失了

如果要禁止重置字段,请将其声明为final,并在静态构造函数中设置:

public final static ImmutableMap<String, String> mapImmutable;

static {
    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); // now we have an error!
    System.out.println(mapImmutable);}
}

另请注意,final 仅防止重置 field/variable,但不会防止对象被修改。如果您有 final HashMap,您仍然可以为其添加 KVP。