栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java Collections.unmodifiableXxx 学习

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java Collections.unmodifiableXxx 学习

Collections.unmodifiableXxx() 创建不可修改的容器对象。 Object newObject = Collections.unmodifiableXxx(object) newObject 只能读,不能修改,但任然可以对 object 进行修改,读 newObject 的值时能够实时看到 对object 修改后的值。 code:
package com.cereb.devicedata;

import java.util.*;

public class Test {
    public static void main(String[] args) {
        ArrayList arrayList = new ArrayList() {{
            add("1");
            add("2");
        }};

        HashMap hashMap = new HashMap() {{
            put("key1", 1);
            put("key2", 2);
        }};

        List unmodifiableList = Collections.unmodifiableList(arrayList);
        Map unmodifiableMap = Collections.unmodifiableMap(hashMap);

        System.out.println(unmodifiableList);
        System.out.println();
        System.out.println(unmodifiableMap);
        System.out.println();

        hashMap.replace("key1", "new 1");
        hashMap.put("key3", 3);

        arrayList.remove(1);
        arrayList.add("3");

        System.out.println(unmodifiableList);
        System.out.println();
        System.out.println(unmodifiableMap);

    }
}

result:
[1, 2]

{key1=1, key2=2}

[1, 3]

{key1=new 1, key2=2, key3=3}

Process finished with exit code 0
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/987974.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号