java基础-unmodifiableList初探

unmodifiableList初探

问题描述:当一个集合在创建成功到使用完成的期间内,内容不允许修改,需要对其进行操作。

如图示:

package cn.com.pep.res.back.YoZo;

import cn.com.pep.res.back.YoZo.vo.UserResBean;
import cn.com.pep.res.back.YoZo.vo.YozoResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.Feature;
import com.sun.istack.internal.Nullable;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * Date: 2021/7/1 15:54
 * author: songyl
 */
public class Test {

    public static void main(String[] args) {
        unModifyTest();
    }

    private static void unModifyTest() {
        List<String> couresList = new ArrayList<>();
        couresList.add("English");
        couresList.add("语文");
        Student student = new Student();
        student.setAge("11");
        student.setName("songyl");
        student.setCources(couresList);
        System.out.println(student);
        List<String> cources = student.getCources();
        cources.add("math");
        System.out.println(student);
    }

    static class Student {
        @Override
        public String toString() {
            return "Student{" +
                    "name='" + name + '\'' +
                    ", age='" + age + '\'' +
                    ", cources=" + cources +
                    '}';
        }

        public Student(String name, String age, List<String> cources) {
            this.name = name;
            this.age = age;
            this.cources = cources;
        }
        String name;
        String age;
        List<String> cources;

        public Student() {

        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getAge() {
            return age;
        }

        public void setAge(String age) {
            this.age = age;
        }

        public List<String> getCources() {
            return cources;
        }

        public void setCources(List<String> cources) {
            this.cources = cources;
        }
    }

}

结果如下
在这里插入图片描述
解决办法:使用colletions.unmodifiableList方法对集合进行处理

        List<String> cources = Collections.unmodifiableList(student.getCources());

再次运行结果如下
在这里插入图片描述
有效的抛出了异常,防止数据被破坏

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值