与迭代器的ConcurrentModificationException

rob*_*del 2 java spring-data-jpa

在我有一个DTO

public class ProductTypesDto extends BaseDto {
  private List<Integer> colors = new ArrayList<>();
  ...
}
Run Code Online (Sandbox Code Playgroud)

在我的豆子里

@Entity
public class ProductTypes 
   @ManyToMany
   private Set<Colors> colors = new HashSet<>();
   ...
}
Run Code Online (Sandbox Code Playgroud)

用户可以添加和删除颜色 productTypes

在DTO to bean转换中,我这样做

private void convertToBeans(ProductTypesDto dto, ProductTypes beans) {
    //add element
    for (Integer color : dto.getColors()) {
        if (beans.getColors().stream().noneMatch(e -> Objects.equals(e.getId(), color))) {
            Optional<Colors> optColors = colorsRepository.findById(color);
            if (optColors.isPresent()) {
                beans.addColor(optColors.get());
            }
        }
    }
    //remove element
    for (Iterator<Colors> iterator = beans.getColors().iterator(); iterator.hasNext();) {
        Colors color = iterator.next();

        if (dto.getColors().stream().noneMatch(e -> e.intValue() == color.getId())) {

            Optional<Colors> optColors = colorsRepository.findById(color.getId());
            if (optColors.isPresent()) {
                beans.removeColor(optColors.get());
            }

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当代码运行时,我明白了

java.util.ConcurrentModificationException:null

好像在iterator.next()上得到这个 ;

Kar*_*cki 5

您不能通过beans.getColors()调用beans.removeColor()最有可能执行的操作来迭代收集并从中删除colors.remove().

要从基础集合中删除当前遍历的元素,请使用Iterator.remove()方法,例如,替换:

beans.removeColor(optColors.get());
Run Code Online (Sandbox Code Playgroud)

有:

iterator.remove();
Run Code Online (Sandbox Code Playgroud)