具有优先级 Queue/ArrayList 的 IndexOutOfBoundsException

IndexOutOfBoundsException with Priority Queue/ArrayList

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

我已尝试尽可能多地更改优先级队列和 ArrayList 的创建方式以及它们所在的位置 created/updated,并且在不更改整个代码的情况下仍然可以正常运行。如果我注释掉 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.

错误行包含 map.cells[r+1][c],因此请检查此单元格二维数组的维度,是否 r+1c 导致此