Java 不可变集合 [英] Java Immutable Collections

查看:31
本文介绍了Java 不可变集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自 Java 1.6 Collection Framework 文档:

不支持任何修改操作(例如addremoveclear)的集合被称为unmodifiable.[...] 额外保证 Collection 对象中的任何更改都不可见的集合被称为不可变.

Collections that do not support any modification operations (such as add, remove and clear) are referred to as unmodifiable. [...] Collections that additionally guarantee that no change in the Collection object will ever be visible are referred to as immutable.

第二个标准让我有点困惑.鉴于第一个集合是不可修改的,并且假设原始集合引用已被处理掉,那么第二行中引用的更改是什么?它是指集合中元素的变化,即元素的状态吗?

The second criteria confuses me a bit. Given the first collection is unmodifiable, and assuming that the original collection reference has been disposed away, what are the changes that are referred to in the second line? Is it referring to the changes in the elements held in the collection ie the state of the elements?

第二个问题:
对于不可变的集合,如何提供指定的额外保证?如果集合中元素的状态由线程更新,那么状态中的那些更新在持有不可变集合的线程上不可见是否足以实现不变性?

Second question:
For a collection to be immutable, how does one go about providing the additional guarentees specified? If the state of an element in the collection is updated by a thread, is it sufficient for immutability that those updates in the state are not visible on the thread holding the immutable collection?

对于不可变的集合,如何提供指定的额外保证?

推荐答案

不可修改的集合通常是其他集合的只读视图(包装器).您无法添加、删除或清除它们,但基础集合可以更改.

Unmodifiable collections are usually read-only views (wrappers) of other collections. You can't add, remove or clear them, but the underlying collection can change.

不可变集合根本不能改变——它们不包装另一个集合——它们有自己的元素.

Immutable collections can't be changed at all - they don't wrap another collection - they have their own elements.

这里引用了 guava 的 ImmutableList

Here's a quote from guava's ImmutableList

Collections.unmodifiableList(java.util.List<? extends T>)不同,它是一个单独的集合的视图,仍然可以改变,一个ImmutableList 包含自己的私人数据,永远不会改变.

Unlike Collections.unmodifiableList(java.util.List<? extends T>), which is a view of a separate collection that can still change, an instance of ImmutableList contains its own private data and will never change.

因此,基本上,为了从可变集合中获取不可变集合,您必须将其元素复制到新集合中,并禁止所有操作.

So, basically, in order to get an immutable collection out of a mutable one, you have to copy its elements to the new collection, and disallow all operations.

这篇关于Java 不可变集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆