Collections.unmodifiableList用于构造一个不能修改的List,实例如下:
package collection; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class CollectionDemo { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("a"); List<String> unmodifiableList = Collections.unmodifiableList(list); unmodifiableList.add("b"); } }
运行后效果如下:
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableCollection.add(Unknown Source)
at collection.CollectionDemo.main(CollectionDemo.java:13)
list在使用unmodifiableList包装后将不能进行修改,修改后会报错。