关于collections.unmodifiablemap 的一点理解
2017-05-30 16:19
946 查看
这是collections.unmodifiablemap的API文档
简单来说就是返回一份map的只读视图,任何企图修改map的操作都会直接返回UnsupportedOperationException。
其实这个不可修改的Map指的是Map本身不可修改,里面的对象若支持修改的话,其实也还是可以修改的。
unmodifiableMap是Map接口的一个实现类,里面包装了一个map对于可能修改map的方法
通过下面的两段代码说明一下(代码和collections.unmodifiablemap 关系不大,只是增加一点理解)
上例中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来防止修改。
相关文章推荐
- 关于Collections.unmodifiableMap的一些理解
- 关于map与set的一点理解;
- Collections.unmodifiableMap()的理解
- 关于销售的一点理解
- 关于JDK动态代理的一点理解
- mAP的一点理解
- 关于 数据文件自增长 的一点理解
- 关于修改 commit_write 提升性能的一点理解
- 关于指针的一点理解(本人小白用户)
- 关于SVM的一点个人理解
- 关于子网掩码的一点理解
- 关于rman备份保留策略“恢复窗口”的一点理解
- 关于路由的一点理解,还有编址
- Collections.unmodifiableMap()的简单解释
- 关于指针数组、数组指针、及函数指针和指向函数指针数组的指针的一点理解
- 关于socket编程的一点心得理解
- 关于java中多线程的一点理解
- 关于过渡机制的一点理解
- 关于linux0.12临界资源的一点理解和猜测
- 关于OO的一点理解