Collections.unmodifiableXxx() 创建不可修改的容器对象。
Object newObject = Collections.unmodifiableXxx(object)
newObject 只能读,不能修改,但仍然可以对 object 进行修改,读 newObject 的值时能够实时看到 对object 修改后的值。
code:
package com.cereb.devicedata;
import java.util.*;
public class Test {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<String>() {{
add("1");
add("2");
}};
HashMap<String, Object> hashMap = new HashMap<String, Object>() {{
put("key1", 1);
put("key2", 2);
}};
List<String> unmodifiableList = Collections.unmodifiableList(arrayList);
Map<String, Object> unmodifiableMap = Collections.unmodifiableMap(hashMap);
System.out.println(unmodifiableList);
System.out.println();
System.out.println(unmodifiableMap);
System.out.println();
hashMap.replace("key1", "new 1");
hashMap.put("key3", 3);
arrayList.remove(1);
arrayList.add("3");
System.out.println(unmodifiableList);
System.out.println();
System.out.println(unmodifiableMap);
}
}
result:
[1, 2]
{key1=1, key2=2}
[1, 3]
{key1=new 1, key2=2, key3=3}
Process finished with exit code 0