Order order=orderService.findOrderById(oid); List<Goods>goodsList=order.getGoodsList(); for (Goods goods:goodsList) { if(goods.getId()==gid){ System.out.println(gid+"----------------------------------------+++++++++++++++++++++++++++++++"); goodsList.remove(goods); break; } } order.setGoodsList(goodsList); orderService.save(order); System.out.println(orderService.findOrderById(oid).getGoodsList()); if(order.getGoodsList().size()==0){ orderService.deleteOrderById(oid); return Result.success(true); } order.setGoodsList(goodsList); return Result.success(true); }这段代码报不能删除
时间: 2023-06-18 08:04:06 浏览: 152
order-product:Nest.js挑战
这段代码报错的原因可能是在对 `goodsList` 进行遍历删除时,使用了 `remove` 方法,这样会改变集合的大小,导致遍历出现问题。可以考虑使用迭代器或者倒序遍历来避免这个问题,例如:
```
Iterator<Goods> iterator = goodsList.iterator();
while (iterator.hasNext()) {
Goods goods = iterator.next();
if (goods.getId() == gid) {
iterator.remove();
break;
}
}
```
或者:
```
for (int i = goodsList.size() - 1; i >= 0; i--) {
Goods goods = goodsList.get(i);
if (goods.getId() == gid) {
goodsList.remove(i);
break;
}
}
```
另外,注意在删除商品后要判断 `goodsList` 是否为空,可以改为 `if (goodsList.isEmpty())`。最后,不需要再次设置 `order.setGoodsList(goodsList)`,因为已经在删除商品时修改了 `order` 的 `goodsList`。
阅读全文