我正在编写一小段代码并遇到了与数组索引超出范围异常相关的奇怪案例。
我在下面解释过。
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)我的问题是,为什么会出现这种奇怪的行为?
答案 0 :(得分:1)
问题是您正在修改distanceToVerticesArr
方法中的getVertexDistanceIndex
引用。所以,在这种情况下:
int VertexDistanceIndex =getVertexDistanceIndex(neighbour);
distanceToVerticesArr[VertexDistanceIndex] = distanceToNeighbour + minDistance;
当它到达第二行时,distanceToVerticesArr
指向新数组,但是当你这样做时:
distanceToVerticesArr[getVertexDistanceIndex(neighbour)] = distanceToNeighbour + minDistance;
已经评估了distanceToVerticesArr
的值,因此将使用旧值,这当然指向一个太小的数组。在执行该行之后将更新数组指针,但为时已晚。解决方案是:a)使用第一种方法,或b)编写更好的代码。