容器的同步控制与只读设置

一.同步控制: 用于多线程并发访问容器资源的线程安全

常用的容器ArrayList HashMap HashSet都是线程不安全的
Collections 中提供了SynchronizedXxx() 方法用于包装容器为同步的 

List<String> list = new ArrayList<String>();
        
List<String> list2 = Collections.synchronizedList(list); // list为线程安全

二.容器只读控制

  容器只读设置 util包下的Collections提供了三种办法:
   (1) emptyXxx()
   (2) singletonXxx()
   (3) unmodifiableXxx()

Map<String , String> map = new HashMap<String ,String>();
        map.put("num1", "value1");
        map.put("num2", "value2");
        map = Collections.unmodifiableMap(map); // 不能再更改容器内容 ,只允许读取
        map.put("num3", "value3");   // 此行会报错
        
        List<String> list3 = Collections.singletonList(new String());
        list3.add("rimon1");
        list3.add("rimon2");  // 只能添加一个元素
    
        
    }
    public static Set<String> emp(Set<String> set){
        if(set == null){
            return Collections.EMPTY_SET;  //防止出现 nullpointerException
        }
        return set;

 

转载于:https://www.cnblogs.com/rimonzheng/p/6785252.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值