Arraylist IndexOutOfBounds调试错误

时间:2015-03-07 03:41:45

标签: java debugging arraylist

我收到以下错误。

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
    at java.util.ArrayList.rangeCheck(Unknown Source)
    at java.util.ArrayList.set(Unknown Source)
    at shortestPath.runQ5(shortestPath.java:181)
    at shortestPath.main(shortestPath.java:26)

提供该问题的代码如下:

 public ArrayList<Integer[]> runQ5() throws Exception   
   {        
       int oldPathCost = 0, pathCost = 0;
       ArrayList<Integer[]> temporary = new ArrayList<Integer[]>();       

       for(int i=1; i<stationNames.size(); i++)
       {
           for(int j=1; j<stationNames.size() & i != j; j++)
           {
               pathCost = runQ3(stationNames.ceilingKey(i), stationNames.ceilingKey(j));

               if(pathCost > oldPathCost)
               {
                   System.out.println(i + ", " + j + ", " +temporary.size());
                   oldPathCost = pathCost;
                   temporary.set(temporary.size(), new Integer[]{i,j});
               }
               else if(pathCost == oldPathCost)
               {
                   oldPathCost = pathCost;
                   temporary.add(new Integer[]{i,j});
               }

           }
       }

       Q6 = oldPathCost + Q6;
       return temporary;
   }

1 个答案:

答案 0 :(得分:1)

没有意义:

temporary.set(temporary.size(), new Integer[]{i,j});

set用于替换列表中现有位置的值,但如果列表的当前大小为temporary.size(),则temporary.size()第三个索引为还没有被占用。

只需写下:

temporary.add(new Integer[]{i,j});

如果您想在列表中设置temporary.size()&#39;元素。