-1

我正在编写一小段代码,遇到了一个与数组索引越界异常相关的非常奇怪的案例。

我已经在下面解释过了。

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)我的问题是,为什么会出现这种奇怪的行为?

4

1 回答 1

1

问题是您正在修改方法distanceToVerticesArr内的引用getVertexDistanceIndex。所以,在这种情况下:

int VertexDistanceIndex =getVertexDistanceIndex(neighbour);
distanceToVerticesArr[VertexDistanceIndex] = distanceToNeighbour + minDistance;

当它到达第二行时,distanceToVerticesArr它指向新数组,但是当你这样做时:

distanceToVerticesArr[getVertexDistanceIndex(neighbour)] = distanceToNeighbour + minDistance;

的值distanceToVerticesArr已经被计算过了,所以将使用旧值,这当然是指向一个太小的数组。数组指针将在行执行后更新,但为时已晚。解决方案是:a) 使用第一种方法,或 b) 编写更好的代码。

于 2013-04-12T10:44:30.513 回答