java對(duì)象中primitive類型變量可以通過(guò)不提供set方法保證不被修改,但對(duì)象的List成員在提供get方法后,就可以隨意add、remove改變其結(jié)構(gòu),這不是希望的結(jié)果。網(wǎng)上看了下,發(fā)現(xiàn)Collections的靜態(tài)方法unmodifiableList可以達(dá)到目的。方法原型為:public static <T> List<T> unmodifiableList(List<? extends T> list);用法也很簡(jiǎn)單,傳入一個(gè)List實(shí)例la,返回這個(gè)list的只讀視圖lb,類型依然是List。之后對(duì)lb進(jìn)行add、remove等改變其內(nèi)容的操作將導(dǎo)致編譯不通過(guò)。
首先舉例描述問(wèn)題:
Student.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
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(); } } |
執(zhí)行結(jié)果:
Alice
18
Math
Chinese
Alice
18
Math
Chinese
English
雖然只有g(shù)etCourse,但依然可以被加上1門English。使用unmodifiableList可以解決這個(gè)問(wèn)題,將Student的getCourses改寫:
1
2
3
|
public List<String> getCourses(){ return Collections.unmodifiableList( this .courses); } |
再次執(zhí)行,編譯器提示出錯(cuò):
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableCollection.add(Collections.java:1055)
總結(jié),使用unmodifiableList可以保證對(duì)象的list內(nèi)容不被意料之外地修改,保證對(duì)象的封裝性。
以上這篇淺談java中unmodifiableList方法的應(yīng)用場(chǎng)景就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持服務(wù)器之家。