执行ITSPoI allowedPoi = j.next()
后,行allowedPoIs.remove(k)
会出现以下错误:
java.util.ConcurrentModificationException at java.util.ArrayList $ Itr.checkForComodification(Unknown Source)
private Map<String,Integer> findClosest(Route tempRoute, List<ITSPoI> allowedPoIs, List<ITSPoI> tabulist) {
double cost,mincost = 999999999;
Map<String,Integer> closest = new HashMap<String,Integer>();
for (int i=0; i<tempRoute.getPOIs().size(); i++) {
int k = 0;
for(Iterator<ITSPoI> j = allowedPoIs.iterator(); j.hasNext(); ) {
ITSPoI allowedPoi = j.next();
if (!intabu(allowedPoi,tabulist))
{
try
{
cost = _cvrtw.getCostMatrix().getCost(tempRoute.getPOI(i).getNodeId(),allowedPoi.getNodeId());
if (cost<mincost){
mincost = cost;
closest.put("index",i);
closest.put("poi",k);
allowedPoIs.remove(k);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
k++;
}
}
return closest;
}
答案 0 :(得分:4)
在循环中运行时,无法从allowedPoIs
中删除元素。将其从iterator
中删除,如:
j.remove();
代替allowedPoIs.remove(k);
我会用while
编写此方法以使其更清晰:
private Map<String,Integer> findClosest(Route tempRoute, List<ITSPoI> allowedPoIs, List<ITSPoI> tabulist) {
double cost,mincost = 999999999;
Map<String,Integer> closest = new HashMap<String,Integer>();
Iterator<ITSPoI> iter;
for (int i=0; i<tempRoute.getPOIs().size(); i++) {
int k = 0;
iter = allowedPoIs.iterator();
while(iter.hasNext()){
ITSPoI allowedPoi = iter.next();
if (!intabu(allowedPoi,tabulist))
{
try
{
cost = _cvrtw.getCostMatrix().getCost(tempRoute.getPOI(i).getNodeId(),allowedPoi.getNodeId());
if (cost<mincost){
mincost = cost;
closest.put("index",i);
closest.put("poi",k);
iter.remove(); // fix
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
k++;
}
}
return closest;
}