gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 07:22:38 25 4
gpt4 key购买 nike

考虑以下代码:

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

关于java - 即使使用迭代器后也会出现并发修改异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31666720/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com