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

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

问题描述

Java 1.6集合框架文档


不支持任何修改操作的集合(例如 add 删除清除)被称为不可修改。 [...]另外保证集合对象不会变为可见的集合称为不可变

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?

(突出显示第二个问题的焦点):

Edit : (highlighting the focus of second question) :

对于集合是不可变的,如何提供额外的指定? / strong>

For a collection to be immutable, how does one go about providing the additional guarentees specified?

推荐答案

不可修改的集合通常是其他集合的只读视图(包装器)。您不能添加,删除或清除它们,但底层集合可以更改。

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天全站免登陆