日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Collections.unmodifiableMap

發(fā)布時間:2024/9/21 编程问答 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Collections.unmodifiableMap 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

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 能做什么?

在《重構-改善既有代碼邏輯》一書中提到了封裝集合的功能(Encapsulate?Collection)。

我們在類中經(jīng)常需要返回一個集合,比如mapA。如果直接返回成員變量mapA本身的話,相當于對外暴露了集合的引用,外部就可以隨意修改該對象的集合,該對象可能對修改都一無所知,屬性卻發(fā)生了變化。

一種解決方法,就是將該集合修飾為private, 在返回集合的方法中采用Collections.unmodifiableMap(mapA),返回mapA的一個不可變的副本。且該方法要比我們自己去復制一個副本效率要高。

3.?Collections.unmodifiableMap 構造的map真的不可修改嗎?

遺憾的是該結論并不總是成立。對于map<key, value>中的內容value,?unmodifiableMap僅僅保證的是它的引用不能被修改,如果value對應的是一個可變對象,那么該unmodifiableMap的內容還是可變的。見實例:

?

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, 但對該對象內容作了修改,unmodifiableMap并未阻止該行為。unmodifiableMap的內容變?yōu)榱?/p>

{jerry=Student{name='jerry', age=1}, tom=Student{name='tom', age=11}}

所以為了線程安全,在使用Collections.unmodifiableMap的同時,盡量讓其中的內容實現(xiàn)為不可變對象。

?

?

轉載于:https://www.cnblogs.com/dreamysmurf/p/6253737.html

總結

以上是生活随笔為你收集整理的Collections.unmodifiableMap的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內容還不錯,歡迎將生活随笔推薦給好友。