浅谈java中unmodifiableList方法的应用场景
java对象中primitive类型变量可以通过不提供set方法保证不被修改,但对象的List成员在提供get方法后,就可以随意add、remove改变其结构,这不是希望的结果。网上看了下,发现Collections的静态方法unmodifiableList可以达到目的。方法原型为:public static <T> List<T> unmodifiableList(List<? extends T> list);用法也很简单,传入一个List实例la,返回这个list的只读视图lb,类型依然是List。之后对lb进行add、remove等改变其内容的操作将导致编译不通过。
Student.java
1 package com.test; 2 3 import java.util.ArrayList; 4 import java.util.Collections; 5 import java.util.List; 6 7 /** 8 * Created by Liulei on 2017/5/31. 9 */ 10 public class Student { 11 private String name; 12 private int age; 13 private List<String> courses; 14 15 public Student(){ 16 courses = new ArrayList<String>(); 17 } 18 public Student(String name,int age,List<String> courses){ 19 this.name = name; 20 this.age = age; 21 this.courses = courses; 22 } 23 24 public List<String> getCourses(){ 25 return this.courses; 26 } 27 28 public void setName(String name) { 29 this.name = name; 30 } 31 32 public void setAge(int age) { 33 this.age = age; 34 } 35 36 public String getName() { 37 return name; 38 } 39 40 public int getAge() { 41 return age; 42 } 43 44 public void describe(){ 45 System.out.println(this.name); 46 System.out.println(this.age); 47 for (String course:courses){ 48 System.out.println(course); 49 } 50 } 51 52 53 }
App.java
1 package com.liulei.test; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 /** 7 * Hello world! 8 * 9 */ 10 public class App 11 { 12 public static void main( String[] args ) 13 { 14 ArrayList<String> courses = new ArrayList<String>(); 15 courses.add("Math"); 16 courses.add("Chinese"); 17 18 Student student = new Student("Alice",18,courses); 19 student.describe(); 20 List<String> myCourses = student.getCourses(); 21 myCourses.add("English"); 22 student.describe(); 23 24 } 25 }
结果:
1 Alice 2 3 18 4 5 Math 6 7 Chinese 8 9 Alice 10 11 18 12 13 Math 14 15 Chinese 16 17 English
虽然只有getCourse,但依然可以被加上1门English。使用unmodifiableList可以解决这个问题,将Student的getCourses改写:
1 public List<String> getCourses(){ 2 return Collections.unmodifiableList(this.courses); 3 }
再次执行,编译器提示出错:
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableCollection.add(Collections.java:1055)
总结,使用unmodifiableList可以保证对象的list内容不被意料之外地修改,保证对象的封装性。
此博文转自https://www.jb51.net/article/115065.htm