1. 程式人生 > >向List中資料新增實體物件,實體物件最後一個會把之前的內容覆蓋

向List中資料新增實體物件,實體物件最後一個會把之前的內容覆蓋

錯誤的寫法:(這樣寫等於一直在操作同一個物件,物件中的內容都一樣)

List<CommissionSystem> cList = new ArrayList<CommissionSystem>();

for (Goods goods : gList) {
             CommissionSystem comSystem = coresult.get(goods.getCatelogId());
             if (comSystem != null) {
                            comSystem .setTenantId(tenantId);
                            comSystem .setCode(code);
                            comSystem .setName(goods.getName());
                            comSystem .setCreateDate(new Date());
                            comSystem .setSn(goods.getCatelogId());
                            comSystem .setGoodsSn(goods.getBarcode());
                            comSystem .setCreateUser(getCurrentUser().getUserName());
                            cList.add(comSystem );
           }
 }

正確的寫法:

List<CommissionSystem> cList = new ArrayList<CommissionSystem>();

for (Goods goods : gList) {
             CommissionSystem comSystem = coresult.get(goods.getCatelogId());
             if (comSystem != null) {
                            CommissionSystem cSystem = new CommissionSystem();
                            BeanUtils.copyProperties(comSystem,cSystem, new String[] { "id", "createDate", "modifyDate" });
                            cSystem.setTenantId(tenantId);
                            cSystem.setCode(code);
                            cSystem.setName(goods.getName());
                            cSystem.setCreateDate(new Date());
                            cSystem.setSn(goods.getCatelogId());
                            cSystem.setGoodsSn(goods.getBarcode());
                            cSystem.setCreateUser(getCurrentUser().getUserName());
                            cList.add(cSystem);
           }
 }