The primitive type variable in the
Java object can be guaranteed not to be modified by not providing a set method, but the list member of the object can arbitrarily add, remove to change its structure after providing the Get method, which is not the desired result. Looked on the net, found collections static method Unmodifiablelist can achieve the goal. Method prototypes are: Public static <t> list<t> unmodifiablelist (list<? extends T> list); Span style= "font-family: Song Body" > method is also very simple, passed in a list instance la , return this list Span style= read-only view of "font-family: Arial" > lb list < span> lb font-family add , remove
The first example describes the problem:
Student.java
Packagecom.liulei.test;Importjava.util.ArrayList;Importjava.util.Collections;Importjava.util.List;/*** Created by Liulei on 2017/5/31.*/ Public classStudent {PrivateString name; Private intAge ; PrivateList<string>courses; PublicStudent () {Courses=NewArraylist<string>(); } PublicStudent (String name,intAge,list<string>courses) { This. Name =name; This. Age =Age ; This. courses =courses; } PublicList<string>getcourses () {return This. Courses; } Public voidsetName (String name) { This. Name =name; } Public voidSetage (intAge ) { This. Age =Age ; } PublicString GetName () {returnname; } Public intGetage () {returnAge ; } Public voiddescribe () {System.out.println ( This. Name); System.out.println ( This. Age); for(String course:courses) {System.out.println (course); } }}
App.java
Packagecom.liulei.test;Importjava.util.ArrayList;Importjava.util.List;/*** Hello world! **/ Public classapp{ Public Static voidMain (string[] args) {ArrayList<String> courses =NewArraylist<string>(); Courses.add ("Math"); Courses.add ("Chinese"); Student Student=NewStudent ("Alice", 18, courses); Student.describe (); List<String> mycourses =student.getcourses (); Mycourses.add ("中文版"); Student.describe (); }}
Execution Result:
Alice
18
Math
Chinese
Alice
18
Math
Chinese
中文版
Although only GetCourse, but still can be added 1 Chinese. Using unmodifiablelist can solve this problem and rewrite the Student getcourses :
Public List<string> getcourses () { return collections.unmodifiablelist ( this . courses); }
Execute again, the compiler prompts an error:
Exception in thread "main" java.lang.UnsupportedOperationException
At Java.util.collections$unmodifiablecollection.add (collections.java:1055)
In summary, the use of unmodifiablelist can ensure that the object's list content is not modified unexpectedly, guaranteeing the encapsulation of the object.
Application scenarios for unmodifiablelist methods in Java