google的ImmutableList和Collections.unmodifiableList()有什么区别? [英] What is the difference between google's ImmutableList and Collections.unmodifiableList ()?

查看:345
本文介绍了google的ImmutableList和Collections.unmodifiableList()有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自ImmutableList javadocs:



不同Collections.unmodifiableList(java.util.List),
是一个单独的
集合的视图仍然可以更改,一个
实例ImmutableList包含其
自己的私有数据,永远不会
更改。 ImmutableList对于公共静态最终列表
(常量列表)方便
,并且允许
轻松地对由你的类提供的
列表进行防御性复制
调用者。


这是否意味着:


  1. 如果我有ImmutableList的Dimension对象(例如),那么我不能更改任何Dimension对象在其中?

  2. 如果我有Collections.unmodifiableList的Dimension对象,那么我不仅可以添加或删除任何对象,但我可以更改它们(例如调用setDimension(width,height)方法)?


不,不变性只适用于集合中对象的数量和引用,而不会解决你放在集合中的对象的可变性。 p>

不可变列表比标准JDK Collections.unmodifiableList获得的是,通过使用ImmutableList,可以保证引用的对象,它们的顺序和列表的大小不能从任何源。对于Collections.unmodifiableList,如果其他对引用列表的引用,那么即使你有一个不可修改列表的引用,该代码也可以修改列表。



,你想要真正的不变性,你必须用不可变的对象填充列表。


From ImmutableList javadocs:

Unlike Collections.unmodifiableList(java.util.List), 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. ImmutableList is convenient for public static final lists ("constant lists") and also lets you easily make a "defensive copy" of a list provided to your class by a caller.

Does it mean that:

  1. if I have ImmutableList of Dimension objects (for example) then I can't change any Dimension object in it?
  2. and if I have Collections.unmodifiableList (list) of Dimension objects then I can't only add or delete any object but I can change them (for example call setDimension(width, height) method)?

解决方案

No, the immutability is only applied to the amount and references of the objects in the Collection, and does not address the mutability of objects you put in the Collection.

What Immutable list gains over the standard JDK Collections.unmodifiableList is that by using ImmutableList you are guaranteed that the objects referenced, their order and the size of the list cannot change from any source. With Collections.unmodifiableList if something else has a reference to the underlying list, that code can modify the list even though you have a reference to an unmodifiable list.

If, however, you want true immutability, you have to fill the list with immutable objects.

这篇关于google的ImmutableList和Collections.unmodifiableList()有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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