Collections.unmodifiableMap

public class UnmodifiedMapDemo {
    private Map<String,Person> personMap;

    public UnmodifiedMapDemo(){
        this.personMap = new HashMap();      
        personMap.put("3",new Person(3,"lr"));
    }

    public Map getPersonMap() {
        return Collections.unmodifiableMap(this.personMap);
    }

    public void setPersonMap(Map personMap) {
        this.personMap = personMap;
    }

    public void changeMap(){
        personMap.put("4",new Person(4,"testChange"));
    }

    public void printMap(){
        System.out.println("******");
        System.out.println("类中原始的map");
        for(String key:personMap.keySet()){
            System.out.println(personMap.get(key));
        }
    }

    public static  void main(String[] args){
        UnmodifiedMapDemo test = new UnmodifiedMapDemo();
        Map<String,Person> umMap = test.getPersonMap();

        System.out.println("******");
        System.out.println("最原始的数据");
        for(String key:umMap.keySet()){
            System.out.println(umMap.get(key));
        }

        //修改map中的对象
        Person person = umMap.get("3");
        person.setAge(55);

        test.changeMap();

        System.out.println("******");
        System.out.println("修改后的数据");
        for(String key:umMap.keySet()){
            System.out.println(umMap.get(key));
        }
        try {
            umMap.put("5",new Person(11,"testAdd"));
        }catch (UnsupportedOperationException e){
            System.out.println("操作被拒绝");
        }

        test.printMap();


    }

}


public class Person {
    private int age;
    private String name;

    public Person(int age, String name) {
        this.age = age;
        this.name = name;
    }
}

执行结果:

******
最原始的数据
lr:3 hashCode:460141958
******
修改后的数据
lr:55 hashCode:460141958
testChange:4 hashCode:1163157884
操作被拒绝
******
类中原始的map
lr:55 hashCode:460141958
testChange:4 hashCode:1163157884

 

copyMap = Collections.unmodifiableMap(sourceMap)->相当于copyMap为sourceMap的一个视图(源码中是构造一个final map的引用指向),map修改,视图也会随之更新。不能直接修改视图。但是可以修改视图里面引用的对象。
 


版权声明:本文为weixin_42542762原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。