ListyoyList = cmcMonthReportMapper.listonthReportInfoDTO(yearOnYearReport); List yoyList01 = new ArrayList<>();
想拷贝 yoyList 到yoyList01,
{
"id": 245,
"reportId": 253,
"industryId": 2,
"subjectVersionId": "2203157YR1WBTGXP",
"fillingMode": 2,
"status": 1,
"gmtCreate": "2022-06-08 14:27:31",
"gmtModified": "2022-06-09 22:29:23",
"listFacilityIndustryRela": [
{
"id": 266,
"reportIndustryId": 245,
"facilitiesCode": "220606DXX2C7CZC0",
"facilitiesName": "机组23",
"status": 1,
"gmtCreate": "2022-06-08 14:27:57",
"gmtModified": "2022-06-08 14:27:57"
}
]
},
{
"id": 303,
"reportId": 253,
"industryId": 3,
"subjectVersionId": "2111237926GADM14",
"fillingMode": 2,
"status": 1,
"gmtCreate": "2022-06-08 14:27:31",
"gmtModified": "2022-06-08 14:27:31",
"listFacilityIndustryRela": [
{
"id": 303,
"reportIndustryId": 303,
"facilitiesCode": "220606DXX2C7CZC0",
"facilitiesName": "机组23",
"status": 1,
"gmtCreate": "2022-06-08 14:27:57",
"gmtModified": "2022-06-08 14:27:57"
},
{
"id": 304,
"reportIndustryId": 303,
"facilitiesCode": "220606DXX2C7CZC0",
"facilitiesName": "机组24",
"status": 1,
"gmtCreate": "2022-06-10 17:56:41",
"gmtModified": "2022-06-10 17:56:41"
}
]
}
然后想删除yoyList01里所有的listFacilityIndustryRela,不影响其他数据,
for (MonthReportInfoDTO yoy: yoyList01) {
yoy.getListFacilityIndustryRela().clear();
}
然后发现
yoyList01.addAll(yoyList)
和循环
for (MonthReportInfoDTO yoy: yoyList) {
yoyList01.add(yoy);
}
都是浅拷贝,对原数据都有影响
有两种解决方法
方法一:
调用工具类
yoyList01 = SerializationUtils.deepCopy(yoyList);
package com.sinocarbon.carbondata.utils;
import com.baomidou.mybatisplus.toolkit.IOUtils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Collections;
import java.util.List;
public class SerializationUtils {
@SuppressWarnings("unchecked")
public static List deepCopy(List src) {
ByteArrayOutputStream byteOut = null;
ObjectOutputStream out = null;
ByteArrayInputStream byteIn = null;
ObjectInputStream in = null;
try {
byteOut = new ByteArrayOutputStream();
out = new ObjectOutputStream(byteOut);
out.writeObject(src);
byteIn = new ByteArrayInputStream(byteOut.toByteArray());
in = new ObjectInputStream(byteIn);
return (List) in.readObject();
} catch (Exception ex) {
} finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(byteIn);
IOUtils.closeQuietly(out);
IOUtils.closeQuietly(byteOut);
}
return Collections.emptyList();
}
}
方法二:使用stream流
Listcollect = yoyList.stream().map( items -> { MonthReportInfoDTO dto = new MonthReportInfoDTO(); dto.setListFacilityIndustryRela(null); dto.setFillingMode(items.getFillingMode()); .... return dto; }).collect(Collectors.toList());



