How to ensure that a collection can not be modified

It is easy to imagine modified with the final keyword, we all know

final keyword can be modified classes, methods, member variables, final modified class can not be inherited, final modified method can not be rewritten, modified final member variables must be initialized values, if the member variable is the basic data types, indicating that the variable the value can not be changed, if the member variable is a reference type, then the value of this address references can not be changed, but the contents of the object inside the reference points can still change
.

So, how do we ensure that a collection can not be modified? First we have to clear the set (map, set, list ...) are reference types, so if we use the final modification, then the contents of the collection inside or can be modified.

We can do an experiment:

We can see: We use the final keyword defines a map collection, this time we went inside pass a set of values, the first key-value pair 1,1; after we modified, the keys can be changed to a value of 1 100, that we can modify the value of the collection of the map.

How should we do to ensure that the collection is not modified it?
We can use unmodifiableMap method under the Collections package, by this method returns a map, and can not be amended. He will report java.lang.UnsupportedOperationException wrong.

Similarly: Collections package also provides a method of collection list and set.
Collections.unmodifiableList (List)
Collections.unmodifiableSet (the Set)
--------------------- 

Guess you like

Origin www.cnblogs.com/ly570/p/10954530.html