gpt4 book ai didi

java - Arraylist IndexOutOfBounds 调试错误

转载 作者:行者123 更新时间:2023-12-01 11:49:27 28 4
gpt4 key购买 nike

我收到以下错误。

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

最佳答案

没有意义:

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

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

只需写:

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

如果你想设置列表中的第temporary.size()元素。

关于java - Arraylist IndexOutOfBounds 调试错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28911118/

28 4 0