我宣告了类似的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}
重新分配时应该抛出异常。
您应该区分Map
的不变性和mapImmutable
字段的不变性。
这里: