列表可变性
Since List
是一个接口,它做出的唯一承诺是:“这些是您将获得的方法”。
The List
接口描述了一个mutable列表。请注意,它具有以下功能add()
, set()
and remove()
。但还要注意,这些突变体是指定为“可选”操作 https://docs.oracle.com/javase/8/docs/api/java/util/List.html.
现有的实现List
实际上,接口是不可变的。
List<Integer> mutable = new ArrayList<>();
mutable.add(1);
List<Integer> immutable = Collections.unmodifiableList(mutable);
// try to modify the list
immutable.add(2);
// Exception in thread "main" java.lang.UnsupportedOperationException
Collections.unmodifiableList()
返回一个实例List
执行Collections.UnmodifiableList
.
Collections.UnmodifiableList
转接所有呼叫不可变的 List
功能,正确地底层List
。而它实现了所有mutable List
通过投掷来发挥作用java.lang.UnsupportedOperationException
.
列表元素可变性
如果我们这样做:
List<Date> mutable = new ArrayList<>();
mutable.add(new Date());
List<Date> immutable = Collections.unmodifiableList(mutable);
Date myCoolDate = immutable.get(0);
我们可以变异吗myCoolDate
?绝对地。
myCoolDate.setTime(99999); // works! mutates the original Date object in the `List`.
The List
— 无论是否不变 — 存储对象引用的副本。一旦我们有了对象的引用(Date myCoolDate = immutable.get(0);
),我们可以自由地改变对象。
不可变列表中的项目有没有不变性保证。他们是和以往一样变化无常.