这是collections.unmodifiablemap的API文档
上例中location 和 unmodifiableMap都指向相同的数据, unmodifiableMap不支持修改。但在本例中可以通过unmodifiableMap.get(id).set(x,y)修改map中的元素;可以将SafePoint的x, y设置为final来防止修改。
* 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 * <tt>UnsupportedOperationException</tt>.<p>
简单来说就是返回一份map的只读视图,任何企图修改map的操作都会直接返回UnsupportedOperationException。
其实这个不可修改的Map指的是Map本身不可修改,里面的对象若支持修改的话,其实也还是可以修改的。
unmodifiableMap是Map接口的一个实现类,里面包装了一个map对于可能修改map的方法
通过下面的两段代码说明一下(代码和collections.unmodifiablemap 关系不大,只是增加一点理解)
/**
* Created by Andrew on 2017/5/30.
*/
public class SafePoint {
private int x,y;
private SafePoint(int [] a){ this(a[0],a[1]); }
public SafePoint(SafePoint p){ this(p.get()); }
public SafePoint(int x, int y){
this.x = x;
this.y = y;
}
public synchronized int[] get(){
return new int[]{x,y};
}
public synchronized void set( int x, int y){
this.x = x;
this.y = y;
}
}
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Created by Andrew on 2017/5/30.
*/
public class PublishingVehicleTracker {
private final Map<String,SafePoint> location;
private final Map<String,SafePoint> unmodifiableMap;
public PublishingVehicleTracker(Map<String,SafePoint> location){
this.location = new ConcurrentHashMap<>(location);
this.unmodifiableMap = Collections.unmodifiableMap(this.location);
}
public Map<String,SafePoint>getLocations(){
return unmodifiableMap;
}
public SafePoint getLocation(String id){
return location.get(id);
}
public void setLocation(String id, int x, int y){
if (!location.containsKey(id)){
throw new IllegalArgumentException("invalid vehicle name: "+id);
}
location.get(id).set(x,y);
}
}
上例中location 和 unmodifiableMap都指向相同的数据, unmodifiableMap不支持修改。但在本例中可以通过unmodifiableMap.get(id).set(x,y)修改map中的元素;可以将SafePoint的x, y设置为final来防止修改。