关于Collections.unmodifiableMap的一些理解

来源:互联网 发布:宋灭亡王安石 知乎 编辑:程序博客网 时间:2024/06/05 09:18

最近在研究common-lang下的ClassUtils源代码到时候,下面代码里面使用到了

static {        final Map<String, String> m = new HashMap<String, String>();        m.put("int", "I");        m.put("boolean", "Z");        m.put("float", "F");        m.put("long", "J");        m.put("short", "S");        m.put("byte", "B");        m.put("double", "D");        m.put("char", "C");        m.put("void", "V");        final Map<String, String> r = new HashMap<String, String>();        for (final Map.Entry<String, String> e : m.entrySet()) {            r.put(e.getValue(), e.getKey());        }        <span style="color:#ff0000;">abbreviationMap = Collections.unmodifiableMap(m);        reverseAbbreviationMap = Collections.unmodifiableMap(r);</span>    }
后面查看帮助文档的时候和Collections.unmodifiableMap的代码的时候,Collections.unmodifiableMap返回的是一个不可修改的Map,

通过阅读帖子和实验,其实这个不可修改的Map指的是Map中的对象地址不可修改,里面的对象若支持修改的话,其实也还是可以修改的。

请看两位大神的解释

1.Cameron Skinner

Collections.unmodifiableMap guarantees that the map will not be modified. It's mostly useful if you want to return a read-only view of an internal map from a method call, e.g:

class A {    private Map importantData;    public Map getImportantData() {        return Collections.unmodifiableMap(importantData);    }}

This gives you a fast method that does not risk the client changing your data. It's much faster and more memory efficient than returning a copy of the map. If the client really does want to modify the returned value then they can copy it themselves, but changes to the copy won't be reflected in A's data.

If you are not returning map references to anyone else then don't bother making it unmodifiable unless you are paranoid about making it immutable. You can probably trust yourself to not change it.

2.Don

Cameron Skinner's statement above that "Collections.unmodifiableMap guarantees that the map will not be modified" is actually only partly true in general, although it happens to be accurate for the specific example in the question (only because the Character object is immutable). I'll explain with an example.

Collections.unmodifiableMap actually only gives you protection that the references to objects held in the map cannot be changed. It does that by restricting the 'put' into the map that it returns. However, the original encapsulated map can still be modified from outside the class because Collections.unmodifiableMap does not make any copies of the contents of the map.

In the question posted by Paulo, the Character objects held in the map are luckily unmodifiable. However, in general this may not be true and the unmodifiability advertised by Collections.unmodifiableMap should not be the only safeguard. For instance, see the example below.

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;}}
哈哈,我只是stackoverflow的搬运工!参考帖子:http://stackoverflow.com/questions/3999086/when-is-the-unmodifiablemap-really-necessary


0 0
原创粉丝点击