如果我们有原始的列表,为什么我们可以更改不可修改的列表? [英] Why can we change the unmodifiable list if we have the original one?

查看:150
本文介绍了如果我们有原始的列表,为什么我们可以更改不可修改的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看 Collections 类,我知道当我们使用 unmodifiableList(List list) unmodifiableCollection(Collection c)它不是创建一个新的对象,而是返回同一个对象的引用,并覆盖可以修改 List [添加 addall >, retainAll ...]

所以我运行这个测试:

By looking at the code of Collections class, i got to know that when we are using the method unmodifiableList(List list) or unmodifiableCollection(Collection c) it is not creating a new object but it is returning the reference of the same object and overriding the methods which can modify the List [ add, addall, remove, retainAll ... ]
So i ran this test:

List modifiableList = new ArrayList();
modifiableList.add ( 1 );   
List unmodifiableList = Collections.unmodifiableList( modifiableList );
// unmodifiableList.add(3);  // it will throw the exception 
modifiableList.add ( 2 );       
System.out.println( unmodifiableList );

结果为 [1,2]

现在的问题是为什么它是指同一个对象?为什么不创建新对象?

result is [ 1,2 ] .
Now the point is why it is referring to the same object? Why it don't create a new object?

推荐答案

(底部的任务答案)

当您创建不可修改的列表时,其目的是不应由以外的人(即API的客户端)修改。

When you create an unmodifiable list, the purpose is that it should not be modified by people other than you - i.e. clients of an API.

方法 unmodifiableList(..)创建一个类型为 UnmodifiableList 但这不是一个公共类),它获得原始列表,并将所有的方法委托给它除了的方法将修改它。

the method unmodifiableList(..) creates a new object of type UnmodifiableList (but this is not a public class), which gets the original list, and delegates all methods to it except the methods which would modify it.

正如文档中所述:


返回指定列表的不可修改视图。此方法允许模块为用户提供对内部列表的只读访问。

Returns an unmodifiable view of the specified list. This method allows modules to provide users with "read-only" access to internal lists.

所以,一个例子:你有一个 List 已经检测到并可以操作,并且您想要为他们提供您的API的客户端。但他不应该改变 。所以你有两个选择:

So, an example: You have a List of devices that your API has detected and can operate, and you want to give them a client of your API. But he is not supposed to change them. So you have two options:


  • 给他一份 List 所以即使他修改了它,这不会改变你的列表

  • 给他一个不可修改的集合 - 他不能修改它,

  • give him a deep copy of your List, so that even if he modifies it, this does not change your list
  • give him an unmodifiable collection - he can't modify it, and you spare the creation of a new collection.

现在这里提供问题标题的答案 - 不可修改的列表是一个 。因此,如果您需要向其中添加一个新项目,例如,您发现了一个刚刚插入的新设备,客户端将能够在其不可修改的视图中看到它。

And now here comes the answer to the title of your question - the unmodifiable list is a view of the original collection. So if you need to add a new item to it - say, you have discovered a new device that was just plugged-in, the clients will be able to see it in their unmodifiable view.

这篇关于如果我们有原始的列表,为什么我们可以更改不可修改的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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