解决 List 执行 remove 时报异常 java.lang.UnsupportedOperationException

2022-04-13 15:31:10 浏览数 (1)

一、情况描述

报错如题:

代码语言:javascript复制
java.lang.UnsupportedOperationException: null
	at java.util.Collections$UnmodifiableCollection.removeAll(Collections.java:1068)

报错行定位到下图红框中这行:

代码如下(只是单纯的想 2 个集合求差集):

代码语言:javascript复制
            List<WorkWeight> removeList = Lists.newArrayList();
            workWeightsList.forEach((workWeight -> {
                if (!employeeId.equals(workWeight.getApproverId()) && workWeight.getEmployeeId().equals(employeeId)) { // 当前人提交的不由自己审批的数据
                    removeList.add(workWeight);
                }
            }));
            if (!CollectionUtils.isEmpty(removeList)) {             
                workWeightsList.removeAll(removeList);  // 这行报错
            }

二、解决办法

用 ArrayList 把集合 workWeightsList 再组装,如下图:

代码:

代码语言:javascript复制
            List<WorkWeight> removeList = Lists.newArrayList();
            workWeightsList.forEach((workWeight -> {
                if (!employeeId.equals(workWeight.getApproverId()) && workWeight.getEmployeeId().equals(employeeId)) { // 当前人提交的不由自己审批的数据
                    removeList.add(workWeight);
                }
            }));
            if (!CollectionUtils.isEmpty(removeList)) {
                workWeightsList = new ArrayList<WorkWeight>(workWeightsList);  // 改写这一行
                workWeightsList.removeAll(removeList);
            }
            return new Payload(new PageImpl(workWeightsList, pageable, result.getTotalElements()));

三、这样改写的原因参见:

UnsupportedOperationException报错原因解说 参考:https://www.jianshu.com/p/7f718d900111

0 人点赞