我声明了一个 ImmutableMap 就像
public static ImmutableMap<String, String> mapImmutable;
为该变量分配一个映射
mapImmutable= ImmutableMap.copyOf(map2);
现在,如果我将其他映射分配给这个“mapImmutable”变量。它不会抛出任何异常并且会更新值。
mapImmutable=ImmutableMap.copyOf(map3);
公共(public)类 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);}}
控制台结果 -: {名称=标记} {国家=美国}
重新分配时应该抛出异常。
最佳答案
您应该区分 Map
的不变性和 mapImmutable
字段的不变性。
顾名思义,ImmutableMap
是不可变的,但是在您的代码中,指向映射的字段只是一个常规字段。因此,可以将其重新指定为指向不同的 map 。如果您希望该字段不可变,只需将其标记为final
。
关于java - 将一个Map分配给ImmutableMap后,如何停止或限制重新分配另一个Map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58788058/