简体   繁体   English

对已排序的列表进行排序时,列表迭代会在Java 8中引发ConcurrentModificationException

[英]List iteration throws ConcurrentModificationException in Java 8 when sorting already sorted list

Just in case anyone else has a similar issue, I thought I'd post my issue and solution here. 万一其他人有类似的问题,我想我会在这里发布我的问题和解决方案。

Basically, I had code that was working fine under Java7, but was consistently throwing a ConcurrentModificationException in Java8. 基本上,我的代码在Java7下可以正常工作,但是在Java8中始终抛出ConcurrentModificationException。 The structure was basically this: 结构基本上是这样的:

List<FormatData> formats = service.getFormat(type);
for (FormatData f : formats) {
    /* Do stuff here */
}

However, part of the "Do stuff here" part ended up calling the same service.getFormat(type) function and returning the same list. 但是,“在这里做东西”部分的一部分最终调用了相同的service.getFormat(type)函数并返回了相同的列表。 However, that same function looked up the list but also sorted the list. 但是,该功能可以查询列表,但也可以对列表进行排序。 In Java7, since the list was already sorted, it didn't modify it. 在Java7中,由于列表已经排序,因此它没有修改。 In Java8, it treats re-sorting a sorted list as having been modified. 在Java8中,它将已排序列表的重新排序视为已修改。

My solution was twofold, either one would have worked. 我的解决方案是双重的,任何一个都行得通。 First of all, I moved the sorting away from the retrieve function so I wouldn't waste time - instead I moved it to the load function where it should have been in the first place. 首先,我将排序从检索函数中移开,这样我就不会浪费时间-而是将其移至应该放在第一位的加载函数中。 Secondly, in a lesser used function that returned the same list but sorted differently, I just created a new list, which I then sorted and returned: 其次,在一个较少使用的函数中,该函数返回相同的列表但排序不同,我只是创建了一个新列表,然后对它进行排序并返回:

result = new ArrayList(oldList);
Collections.sort(result, otherComparator);

In addition, before returning on either side, I added this to ensure no more modifications can occur without throwing exceptions: 另外,在任何一方返回之前,我添加了此内容以确保在不引发异常的情况下不会进行更多修改:

result = (result==null) ? null : Collections.unmodifiableList(result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM