即使在使用迭代器后也出现并发修改异常

Getting concurrent modification exception even after using iterator

考虑以下代码:

 if(!unmatchedNewTruckRequirementSet.isEmpty()){
        for(Iterator<TruckRequirement> iterator = unmatchedNewTruckRequirementSet.iterator(); iterator.hasNext();){
            TruckRequirement newTruckRequirement = iterator.next();
            for(Iterator<TruckRequirement> iterator1 = oldTruckRequirementSet.iterator(); iterator1.hasNext();){
                TruckRequirement oldTruckRequirement1 = iterator1.next();
                if(oldTruckRequirement1.getTruckClassName().equals(newTruckRequirement.getTruckClassName())) {
                    LogUtil.logInfo("Truck Requirement Changed ", "Truck Requirement Changed : From : {0} to {1} where Truck Class is: {2}",
                            new Object[]{oldTruckRequirement1.getNumberOfTrucks(), newTruckRequirement.getNumberOfTrucks(), newTruckRequirement.getTruckClassName()});
                    unmatchedNewTruckRequirementSet.remove(newTruckRequirement);
                }
            }LogUtil.logInfo("Truck Requirement Added ", "New Truck Requirement Added with Truck Class : {0} and number of Trucks : {1}",
                    new Object[]{newTruckRequirement.getTruckClassName(), newTruckRequirement.getNumberOfTrucks()});

    }else {
        if(oldTruckRequirementSet.size() > unmatchedNewTruckRequirementSet.size()){
            for(TruckRequirement truckRequirement : oldTruckRequirementSet) {
                LogUtil.logInfo("Truck Requirement Removed ", "Truck Requirement Removed with Truck Class : {0}",
                        new Object[]{truckRequirement.getTruckClassName()});
            }
        }
    }

我已经使用迭代器迭代两个哈希集: unmatchedNewTruckRequiremnetSet,另一个是oldTruckRequirementSet。 当我尝试从 unmatchedNewTruckRequiremnetSet 中删除一个集合时,出现并发修改异常。请帮忙。

如果你在循环中使用Collection.removeadd方法,你将得到ConcurrentModificationException

您必须使用 Iterator.remove() 来删除和避免异常。

for(Iterator<TruckRequirement> iterator1 = oldTruckRequirementSet.iterator(); iterator1.hasNext();){
    TruckRequirement oldTruckRequirement1 = iterator1.next();
    if(oldTruckRequirement1.getTruckClassName().equals(newTruckRequirement.getTruckClassName())) {
        LogUtil.logInfo("Truck Requirement Changed ", 
                "Truck Requirement Changed : From : {0} to {1} where Truck Class is: {2}",
                new Object[]{oldTruckRequirement1.getNumberOfTrucks(), 
                newTruckRequirement.getNumberOfTrucks(), newTruckRequirement.getTruckClassName()});

        // Use the iterator to remove
        iterator1.remove();
    }
}