具有优先级队列/ ArrayList的IndexOutOfBoundsException

时间:2019-05-18 16:35:22

标签: java arraylist indexoutofboundsexception priority-queue

我正在这个项目上做Dijkstra的算法(似乎很多代码,但是我必须使用项目的其他给定类和限制),并且我正在使用优先级队列,该队列将当前节点的邻居顶点进入队列,并以顶点之间的最短距离为优先。它在大多数情况下都可以正常工作,但是当将邻居坐标添加到优先级队列(pq)时,一旦命中7个元素,它将在neighbor.add()行之一中引发ArrayOutOfBoundsException。邻居数组永远不会超过4的长度,并且会在每个循环中重新创建,因此我不认为这是ArrayList删除问题。我对Priority Queue做错了吗,或者实际上是数组列表吗?我对同时使用这两种工具还比较陌生,所以这是我第一次与它们深入合作。

我尝试更改优先级队列和ArrayList的创建方式以及它们在何处创建/更新的方式,并且在不更改整个代码的情况下仍保持其功能。如果我注释掉pq.add(nb)行,则它没有此异常,这使我进一步相信这就是我的问题所在。


Comparator<Coordinate> compareCoord = new Comparator<Coordinate>(){   
     public int compare(Coordinate a, Coordinate b){    
          if(a.getTerrainCost() > b.getTerrainCost())     return 1;   
          if(a.getTerrainCost() < b.getTerrainCost())     return -1;   
          else                                            return 0;   
         }   
};   
 PriorityQueue<Coordinate> pq = new PriorityQueue<>(compareCoord);   

------------------------------------------------------------------------------
//Loop used to repeat through all the vertices   
while(!unVisited.isEmpty()){   
 //Set current vertex to next in PQ and add/remove from appropriate lists   
    Coordinate smallest = pq.poll();   
....   
List<Coordinate> neighbor = new ArrayList<Coordinate>();   
   if(r!=0)        neighbor.add(map.cells[r-1][c]);   
   if(r!=rows)     neighbor.add(map.cells[r+1][c]); //Line of thrown exception   
   if(c!=0)        neighbor.add(map.cells[r][c-1]);   
   if(c!=columns)  neighbor.add(map.cells[r][c+1]);   

 //Run for loop for each neighbor of vertex   
for(Coordinate nb : neighbor){   
   //Check to make sure the neighbor has not already been visited   
   if(!visited.contains(nb)){   
        //Check path length of the current vertex to the neighbor   
        int index = coords.indexOf(nb);   
        Coordinate n = coords.get(index);   
        int nCost = n.getTerrainCost();   
        int altPath = totalCosts.get(smallest) + nCost;   
        //If path is shorter, update variables and add neighbor to priority  queue   
           if(altPath < totalCosts.get(nb)){   
               totalCosts.put(nb,altPath);   
               prevCoord.put(nb,smallest);   
               pq.add(nb); //If commented out, program runs with no exception   
            }   
    }   
}   
-----------------------------------------------------------------------------
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
        at pathFinder.DijkstraPathFinder.<init>(DijkstraPathFinder.java:73)
        at PathFinderTester.main(PathFinderTester.java:294)

Line 73 is commented to find where exception is coming from.

1 个答案:

答案 0 :(得分:0)

错误行包含map.cells[r+1][c],因此请检查此单元格2d数组的尺寸,以确定是否是r+1c引起的