我正在编写一小段代码,遇到了一个与数组索引越界异常相关的非常奇怪的案例。
我已经在下面解释过了。
1)我有一个数组,我试图在一个特定的索引 UNKNOWN 给我分配一些值。
distanceToVerticesArr[getVertexDistanceIndex(neighbour)] = distanceToNeighbour + minDistance;
2)getVertexDistanceIndex()函数如下:
static int getVertexDistanceIndex(String Vertex) {
//This method returns the index at which the distance to a particular vertex is stored in the distanceToVerticesArr
for (int i = 0; i < vertexIndex.size(); i++) {
if (vertexIndex.get(i).toString().equals(Vertex)) {
return i;
}
}
//index not found, hence inserting the vertex
int j = vertexIndex.size();
float[] temp = Arrays.copyOf(distanceToVerticesArr, distanceToVerticesArr.length + 1);
distanceToVerticesArr = new float[temp.length];
distanceToVerticesArr = Arrays.copyOf(temp, temp.length); //length of array = j+1
vertexIndex.put(j, Vertex);
return j;
}
3) 现在,查看注释“未找到索引,因此插入索引”下方的代码。如果我返回值 j,我会在第 1 点提到的调用中得到一个 IndexOutOfBounds 异常。但如果我返回 i,我不会遇到异常。
4)我更进一步,我修改了 POINT 1 中的代码如下:
int VertexDistanceIndex =getVertexDistanceIndex(neighbour);
distanceToVerticesArr[VertexDistanceIndex] = distanceToNeighbour + minDistance;
现在,在这种情况下,无论我返回 i 还是 j,我都没有例外。
5)我的问题是,为什么会出现这种奇怪的行为?