list循环赋值踩坑—list的内容都是一个样
listadd同一个对象时,这个对象需要在循环new,不然list指向的地址永远只有一个!!!
错误
MultipartFile[] files=xxx;
List<tsmFileupLog> arrTsmFileupLogs=new ArrayList<tsmFileupLog>;
TsmFileupLog tsmFileupLog = new TsmFileupLog();
for (MultipartFile file : files) {
tsmFileupLog.setCreateBy(currentUser.getUserName());
tsmFileupLog.setUploadBy(currentUser.getUserName());
tsmFileupLog = tsmFileService.uploadFile(tsmFileupLog, file);
arrTsmFileupLogs.add(tsmFileupLog);
}
正确
MultipartFile[] files=xxx;
List<tsmFileupLog> arrTsmFileupLogs=new ArrayList<tsmFileupLog>;
for (MultipartFile file : files) {
TsmFileupLog tsmFileupLog = new TsmFileupLog();
tsmFileupLog.setCreateBy(currentUser.getUserName());
tsmFileupLog.setUploadBy(currentUser.getUserName());
tsmFileupLog = tsmFileService.uploadFile(tsmFileupLog, file);
arrTsmFileupLogs.add(tsmFileupLog);
}
原因:在循环对象赋值时,需要多次循环new一个对象,在内存中开辟多个内存空间,list下标的指向地址就会不一样
如果只是new一个对象,则内存中只开辟一个内存空间位置,list的指针指向都是一个对象,所以会导致list循环add会全都是一个内容