您可以使用Collections接口的unmodifiableList()方法使集合不可修改。
示例
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Sample {
public static void main(String[] args) {
ArrayList list = new ArrayList();
list.add("JavaFx");
list.add("Java");
list.add("WebGL");
list.add("OpenCV");
System.out.println(list);
List myList= (List) Collections.unmodifiableList(list);
myList.add("Apache Hadoop");
System.out.println(myList);
}
}
输出结果Exception in thread "main" [JavaFx, Java, WebGL, OpenCV]
java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableCollection.add(Unknown Source)
at collections_package.Sample.main(Sample.java:16)