I am having a problem with this iterator on the set. This is a small project that I created with spring Initializer.
I use spring boot with tomcat. Previously I used a for loop and then I saw this answer over here Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop and tried to adapt the first answer to my case.
Only thing is is that I have to decouple the 2 entities Parent and Child from the bidirectional one-to-many, many-to-one relationship before deleting. I am still getting this error even if I use the iterator.
@PostMapping("/savecart")
public ResponseEntity<String> saveCartToDb(@RequestBody Set<CartProduct> cartProductList, Principal principal) {
User logedInUser = userService.findUserByUsername(principal.getName()).get();
Set<CartProduct> cartItemList = logedInUser.getCartProduct();
for (CartProduct cartProduct : cartProductList) {
cartProduct.setUser(logedInUser);
}
userService.saveNewUser(logedInUser);
log.info("In saveCartToDb()");
if (cartItemList.isEmpty()) {
logedInUser.setCartProduct(cartProductList);
userService.saveNewUser(logedInUser);
} else {
for (Iterator<CartProduct> iterator = cartItemList.iterator(); iterator.hasNext();) {
CartProduct cartItem = iterator.next();
if (cartItem != null) {
// Remove the current element from the iterator and the list.
cartItem.dismissParent();
logedInUser.dismissChild(cartItem);
iterator.remove();
userService.saveNewUser(logedInUser);
}
}
// for(CartProduct cartItem : cartItemList){
// cartItem.dismissParent();
// logedInUser.dismissChild(cartItem);
// userService.saveNewUser(logedInUser);
// }
cartProductService.deleteAllProductIds();
for (CartProduct cartProduct : cartProductList) {
cartProduct.setUser(logedInUser);
}
logedInUser.setCartProduct(cartProductList);
userService.saveNewUser(logedInUser);
}
return ResponseEntity.ok().body(cartProductList.toString());
}
The methods that I use to decouple
public void dismissChild(CartProduct child) {
this.cartProduct.remove(child);
}
public void dismissParent() {
this.user.dismissChild(this);
this.user = null;
}
java.util.ConcurrentModificationException: null
at java.base/java.util.HashMap$HashIterator.remove(HashMap.java:1611) ~[na:na]
Is there a way I can modify the iterator no not receive this error anymore? Or is there a better solution that with the iterator?