0

该行在ITSPoI allowedPoi = j.next()执行后提供以下错误allowedPoIs.remove(k)

java.util.ConcurrentModificationException at java.util.ArrayList$Itr.checkForComodification(未知来源)

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; 
    }
4

1 回答 1

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; 
}
于 2013-10-01T07:40:57.767 回答