List<Object> 如何不可修改
时间: 2024-09-08 13:03:24 浏览: 48
在Java中,List<Object>
类型的集合默认是可修改的,意味着你可以通过添加、删除或更新集合中的元素。如果你想要创建一个不可修改的 List<Object>
,你可以使用 Collections 类提供的 unmodifiableList
方法,这个方法可以将任何 List
转变为一个不可修改的视图。下面是如何操作的示例:
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class UnmodifiableListExample {
public static void main(String[] args) {
List<Object> modifiableList = Arrays.asList("Apple", "Banana", "Cherry");
// 创建一个不可修改的List视图
List<Object> unmodifiableList = Collections.unmodifiableList(modifiableList);
// 尝试修改不可修改的List将引发UnsupportedOperationException
// unmodifiableList.add("Date"); // 这行代码会抛出异常
// 输出结果仍然是 ["Apple", "Banana", "Cherry"]
System.out.println(unmodifiableList);
}
}
需要注意的是,unmodifiableList
返回的列表虽然不可修改,但这只是对列表的一个视图。如果原列表(在这个例子中是 modifiableList
)是可变的,那么通过原列表对集合进行修改仍然会影响到不可修改的视图。为了确保整个系统中都是不可修改的,你需要确保不持有对原始可修改列表的引用,并且原始列表本身也不被修改。
相关推荐


















