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
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(); } }
执行结果:
Alice
18
Math
Chinese
Alice
18
Math
Chinese
English
虽然只有getCourse,但依然可以被加上1门English。使用unmodifiableList可以解决这个问题,将Student的getCourses改写:
public List<String> getCourses(){ return Collections.unmodifiableList(this.courses); }
再次执行,编译器提示出错:
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableCollection.add(Collections.java:1055)
总结,使用unmodifiableList可以保证对象的list内容不被意料之外地修改,保证对象的封装性。
时间: 2024-10-24 20:23:49