1. 概述
public static <K,V> Map<K,V> unmodifiableMap(Map<? extends K,? extends V> m)
- 返回指定映射的不可修改视图。此方法允许模块为用户提供对内部映射的“只读”访问。在返回的映射上执行的查询操作将“读完”指定的映射。
-
试图修改返回的映射(不管是直接修改还是通过其 collection 视图进行修改)将导致抛出 UnsupportedOperationException。
如果指定映射是可序列化的,则返回的映射也将是可序列化的。
-
- 参数:
-
- 将为其返回一个不可修改视图的映射。m
返回: - 指定映射的不可修改视图。
-
2. demo
2.1 code (摘自 http://stackoverflow.com/questions/3999086/when-is-the-unmodifiablemap-really-necessary)
package com.rocky.catest;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class SeeminglyUnmodifiable {
private Map<String, Point> startingLocations = new HashMap<String, Point>(3);
public SeeminglyUnmodifiable(){
startingLocations.put("LeftRook", new Point(1, 1));
startingLocations.put("LeftKnight", new Point(1, 2));
startingLocations.put("LeftCamel", new Point(1, 3));
//..more locations..
}
public Map<String, Point> getStartingLocations(){
return Collections.unmodifiableMap(startingLocations);
}
public static void main(String [] args){
SeeminglyUnmodifiable pieceLocations = new SeeminglyUnmodifiable();
Map<String, Point> locations = pieceLocations.getStartingLocations();
Point camelLoc = locations.get("LeftCamel");
System.out.println("The LeftCamel's start is at [ " + camelLoc.getX() + ", " + camelLoc.getY() + " ]");
//Try 1. update elicits Exception
try{
locations.put("LeftCamel", new Point(0,0));
} catch (java.lang.UnsupportedOperationException e){
System.out.println("Try 1 - Could not update the map!");
}
//Try 2. Now let's try changing the contents of the object from the unmodifiable map!
camelLoc.setLocation(0,0);
//Now see whether we were able to update the actual map
Point newCamelLoc = pieceLocations.getStartingLocations().get("LeftCamel");
System.out.println("Try 2 - Map updated! The LeftCamel's start is now at [ " + newCamelLoc.getX() + ", " + newCamelLoc.getY() + " ]"); }
}
class Point{
public float x;
public float y;
public Point(float x, float y){
setLocation(x, y);
}
public void setLocation(float x, float y){
this.x = x;
this.y = y;
}
public float getX(){
return x;
}
public float getY(){
return y;
}
}
2.2 控制台输出
The LeftCamel's start is at [ 1.0, 3.0 ]
Try 1 - Could not update the map!
Try 2 - Map updated! The LeftCamel's start is now at [ 0.0, 0.0 ]
3. 解释
unmodifiableMap方法返回的Map, 它本身不允许修改, 就是说其中每一个entry引用不允许修改,但是entry中的value如果是对象,value引用的对象的属性值是可以修改的
转载于:https://www.cnblogs.com/rocky-fang/p/6702688.html