不可变的vs不可修改的收藏 [英] Immutable vs Unmodifiable collection

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

问题描述

收藏集框架概述


不支持修改操作的集合(如 add 删除 clear )被称为不可修改。不可修改的集合是可修改

Collections that do not support modification operations (such as add, remove and clear) are referred to as unmodifiable. Collections that are not unmodifiable are modifiable.

另外还保证了 Collection 对象将被看见被称为 immutable

Collections that additionally guarantee that no change in the Collection object will be visible are referred to as immutable. Collections that are not immutable are mutable.

我不明白这个区别。

这里不可修改

推荐答案

一个不可修改的集合通常是围绕可修改的集合的封装其他代码可能仍然可以访问。所以,如果您只对不可修改的集合进行引用,那么 不能对其进行任何更改,则不能依赖不更改的内容。

An unmodifiable collection is often a wrapper around a modifiable collection which other code may still have access to. So while you can't make any changes to it if you only have a reference to the unmodifiable collection, you can't rely on the contents not changing.

如果它包装可修改的集合,则确保没有其他代码可以访问该可修改的集合。请注意,尽管没有代码可以更改该集合包含引用的对象,但对象本身仍然可以是可变的 - 创建一个不可变的集合 StringBuilder 不会以某种方式冻结对象。

An immutable collection guarantees that nothing can change the collection any more. If it wraps a modifiable collection, it makes sure that no other code has access to that modifiable collection. Note that although no code can change which objects the collection contains references to, the objects themselves may still be mutable - creating an immutable collection of StringBuilder doesn't somehow "freeze" those objects.

基本上,区别在于其他代码是否可以更改背后的集合。

Basically, the difference is about whether other code may be able to change the collection behind your back.

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

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