java - 带有迭代器的 ConcurrentModificationException

标签 java spring-data-jpa

在 DTO 中我有

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

在我的 bean 里

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

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

在 DTO 到 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());
            }

        }
    }
}

当代码运行时,我得到

java.util.ConcurrentModificationException: null

似乎在 iterator.next(); 上得到这个

最佳答案

您无法迭代 beans.getColors() 集合并通过调用 beans.removeColor() 从中删除,这很可能执行 colors.remove ().

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

beans.removeColor(optColors.get());

与:

iterator.remove();

关于java - 带有迭代器的 ConcurrentModificationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51315184/

相关文章:

java - @Bean注解的使用

java - 如何重写 PropertySourcesPropertyResolver 并向外部化配置添加额外的属性源

java - findBy 在 Instant 中使用 Postgres 时间戳不工作微秒

java - pageRequest 无法通过 root 转换为可分页

java - Spring RestTemplate 将大文件转发到另一个服务

java - 如何测试没有抛出异常?

java - Spring JPA : ManyToMany relationship not stored in database when reuse the property to store another object

java - spring-data-jpa 中的交叉连接

java - 为什么SimpleJdbcCall会忽略@Transactional注解

java - 使用分隔符获取每个数组索引中的子字符串