Collections.unmodifiableMap
1.?Collections.unmodifiableMap 是什么?
Java的官方解釋:
public static?<K,V>?Map<K,V>?unmodifiableMap(Map<? extends K,? extends V>?m) Returns an unmodifiable view of the specified map. This method allows modules to provide users with "read-only" access to internal maps. Query operations on the returned map "read through" to the specified map, and attempts to modify the returned map, whether direct or via its collection views, result in an?UnsupportedOperationException.翻譯過來就是:該方法返回了一個map的不可修改的視圖umap, 為用戶提供了一種生成只讀容器的方法。如果嘗試修改該容器umap, 將會拋出UnsupportedOperationException異常。
2.?Collections.unmodifiableMap 能做什么?
在《重構(gòu)-改善既有代碼邏輯》一書中提到了封裝集合的功能(Encapsulate?Collection)。
我們在類中經(jīng)常需要返回一個集合,比如mapA。如果直接返回成員變量mapA本身的話,相當于對外暴露了集合的引用,外部就可以隨意修改該對象的集合,該對象可能對修改都一無所知,屬性卻發(fā)生了變化。
一種解決方法,就是將該集合修飾為private, 在返回集合的方法中采用Collections.unmodifiableMap(mapA),返回mapA的一個不可變的副本。且該方法要比我們自己去復制一個副本效率要高。
3.?Collections.unmodifiableMap 構(gòu)造的map真的不可修改嗎?
遺憾的是該結(jié)論并不總是成立。對于map<key, value>中的內(nèi)容value,?unmodifiableMap僅僅保證的是它的引用不能被修改,如果value對應的是一個可變對象,那么該unmodifiableMap的內(nèi)容還是可變的。見實例:
?
1 public class UnmodifiableMap { 2 3 public static void main(String[] args) { 4 5 Map<String, Student> map = new HashMap<String, Student>(); 6 Student tom = new Student("tom", 3); 7 map.put("tom", tom); 8 map.put("jerry", new Student("jerry", 1)); 9 10 Map<String, Student> unmodifiableMap = Collections.unmodifiableMap(map); 11 // unmodifiableMap.put("tom", new Student("tom", 11)); // tag1 12 tom.setAge(11); // tag2 13 System.out.println(unmodifiableMap); 14 } 15 16 } 17 18 // mutable 19 class Student { 20 private String name; 21 private int age; 22 23 public Student(String name, int age) { 24 this.name = name; 25 this.age = age; 26 } 27 28 public String getName() { 29 return name; 30 } 31 32 public void setName(String name) { 33 this.name = name; 34 } 35 36 public int getAge() { 37 return age; 38 } 39 40 public void setAge(int age) { 41 this.age = age; 42 } 43 44 @Override 45 public String toString() { 46 return "Student{" + 47 "name='" + name + '\'' + 48 ", age=" + age + 49 '}'; 50 } 51 }?
代碼中Student 對象是可變對象。在tag1處,嘗試更換為另一個對象,引用發(fā)生了變化,會拋出UnsupportedOperationException異常。unmodifiableMap阻止了對其的修改
但如果引用不變,見tag2處,還是tom, 但對該對象內(nèi)容作了修改,unmodifiableMap并未阻止該行為。unmodifiableMap的內(nèi)容變?yōu)榱?/p>
{jerry=Student{name='jerry', age=1}, tom=Student{name='tom', age=11}}
所以為了線程安全,在使用Collections.unmodifiableMap的同時,盡量讓其中的內(nèi)容實現(xiàn)為不可變對象。
?
?
轉(zhuǎn)載于:https://www.cnblogs.com/dreamysmurf/p/6253737.html
總結(jié)
以上是生活随笔為你收集整理的Collections.unmodifiableMap的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 从源码浅析MVC的MvcRouteHan
- 下一篇: winform自定义控件