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修改,视图也会随之更新。不能直接修改视图。但是可以修改视图里面引用的对象。
 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值