Application scenarios of the unmodifiableList method in java and redislist
In a java object, the primitive type variables can be modified without the set method. However, after the Object List members provide the get method, they can add and remove them to change their structure, this is not the expected result. After reading it online, I found that the static method unmodifiableList of Collections can be used. The method is prototype: public static <T> List <T> unmodifiableList (List <? Extends T> list); The usage is also very simple. Input a List instance la and return the read-only lb of this list. The type is still List. Then, add, remove, and other operations on lb to change its content will cause compilation failure.
First, give an example to describe the problem:
Student. java
package com.liulei.test;import java.util.ArrayList;import java.util.Collections;import java.util.List;/** * Created by Liulei on 2017/5/31. */public class Student { private String name; private int age; private List<String> courses; public Student(){ courses = new ArrayList<String>(); } public Student(String name,int age,List<String> courses){ this.name = name; this.age = age; this.courses = courses; } public List<String> getCourses(){ return this.courses; } public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public int getAge() { return age; } public void describe(){ System.out.println(this.name); System.out.println(this.age); for (String course:courses){ System.out.println(course); } }}
App. java
package com.liulei.test;import java.util.ArrayList;import java.util.List;/** * Hello world! * */public class App{ public static void main( String[] args ) { ArrayList<String> courses = new ArrayList<String>(); courses.add("Math"); courses.add("Chinese"); Student student = new Student("Alice",18,courses); student.describe(); List<String> myCourses = student.getCourses(); myCourses.add("English"); student.describe(); }}
Execution result:
Alice
18
Math
Chinese
Alice
18
Math
Chinese
English
Although only getCourse is available, you can still add one English course. UnmodifiableList can solve this problem and rewrite the getCourses of Student:
public List<String> getCourses(){ return Collections.unmodifiableList(this.courses); }
When the code is executed 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 ensures that the list content of an object is not modified unexpectedly and that the object is encapsulated.