我们将首先将列表设置为不可修改,然后在测试之后将其设置为不可修改。让我们创建一个List并添加元素-
List <Integer> list = new LinkedList <Integer> (); list.add(10); list.add(20); list.add(30); list.add(40); list.add(50);
将上面的列表设置为不可修改-
List<Integer>unmodifiable = Collections.unmodifiableList(list);
现在,使用If-else来检查列表是否不可修改-
if (unmodifiable.getClass().getName().contains("UnmodifiableList")) System.out.println("This is an UnmodifiableList" ); else System.out.println("This is not an UnmodifiableList" );
import java.util.Collections; import java.util.LinkedList; import java.util.List; public class Demo { public static void main(String[] args) { List<Integer>list = new LinkedList<Integer>(); list.add(10); list.add(20); list.add(30); list.add(40); list.add(50); List<Integer>unmodifiable = Collections.unmodifiableList(list); if (unmodifiable.getClass().getName().contains("UnmodifiableList")) System.out.println("This is an UnmodifiableList" ); else System.out.println("This is not an UnmodifiableList" ); } }
输出结果
This is an UnmodifiableList