Java – if we have the original list, why can we change the non modifiable list?

By looking at the code of the collections class, I know that when we use the method unmodifiablelist (list list) or unmodifiablecollection (collection C), it does not create a new object, but returns a reference to the same object and overrides the methods that can modify the list [add, addall, remove, retainAll...]

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 );

The result is [1,2] Now the point is why does it refer to the same object? Why not create a new object?

Solution

(answers to questions at the bottom)

When you create an immutable list, the purpose is that it should not be modified by anyone other than you (i.e. the client of the API)

Method unmodifiablelist (..) Create a new object of type unmodifiablelist (but this is not a public class). It gets the original list and delegates all methods to it, except the methods that modify it

The key is, as described in the document:

For example: you have a list of devices that the API detects and can run, and you want to provide clients with APIs for them But he should not change them So you have two choices:

>Give him a deep copy of your list so that even if he modifies it, it won't change your list > give him an immutable set - he can't modify it, you don't have to create a new set

Now you can find the answer to the question title - the immutable list is a view of the original set Therefore, if you need to add a new item to it - for example, if you find a new device that has just been inserted, the client will be able to see it in its unmodifiable view

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>