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

我声明了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}

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

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

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

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

,

这里:

mapImmutable = ImmutableMap.copyOf(map3);

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

ImmutableMap不可变并不表示您可以重置其类型的变量。这仅意味着它的实例将不会更改。例如您不能将新项目添加到地图或从中删除项目。在上一行中,您没有修改ImmutableMap的任何实例,而是通过调用ImmutableMap并将其分配给{来创建copyOf new 实例。 {1}}。 mapImmutable所指的地图未更改,只是丢失

如果要禁止重置字段,请将其声明为mapImmutable,然后在静态构造函数中进行设置:

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,您仍然可以向其中添加KVP。

本文链接:https://www.f2er.com/3129517.html

大家都在问