返回两个int [] []数组但没有得到java.lang.ArrayIndexOutOfBoundsException的技术:-1错误

问题描述 投票:0回答:1

我有一个个人编码问题。我正在尝试在Java中使用前驱矩阵编写Floyd-Warshall算法的代码。我的目标是同时返回我不知道该怎么做的矩阵数组和predMatrix,并且当我只返回一个矩阵矩阵来运行它时,我在java.util.ArrayList处得到indexoutOfboundsException:-1。 java.util.ArrayList.get处的elementData(未知源)(未知源)

public int[][] floydWarshall(Graph g) {     
    ArrayList<Edge> n = g.getEdgeList();

    int[][] matrix = new int[n.size()][n.size()];
    int[][] predMatrix = new int[0][0];
    for(int k = 0; k <= n.size(); k++) {
        for(int i = 0; i < n.size(); i++) {
            for(int j = 0; j < n.size(); j++) {
                String label = n.get(k - 1).getLabel();
                String label2 = n.get(i).getLabel();
                String label3 = n.get(j).getLabel();
                //String predessor = n.get(k).getTail().getName();
                int kDistance = Integer.parseInt(label);
                int iDistance = Integer.parseInt(label2);
                int jDistance = Integer.parseInt(label3);
                if((matrix[iDistance][jDistance] == Integer.MAX_VALUE) &&
                        (matrix[iDistance][kDistance] + matrix[kDistance][jDistance] == Integer.MAX_VALUE)) {
                        continue;
                    //matrix[iDistance][jDistance] = kDistance;
                } else if(matrix[iDistance][jDistance] <= matrix[iDistance][kDistance] + matrix[kDistance][jDistance])
                    matrix[iDistance][jDistance] = matrix[iDistance][jDistance];
                    predMatrix[iDistance][jDistance] = predMatrix[iDistance][jDistance];
                }else {
                    matrix[iDistance][jDistance] = matrix[iDistance][kDistance] + matrix[kDistance][jDistance];
                    predMatrix[iDistance][jDistance] = predMatrix[kDistance][jDistance];

                }
            }
        }
    }
    return matrix;
}
java algorithm shortest-path floyd-warshall
1个回答
0
投票

IndexOutOfBoundsException发生是因为您在for循环中设置了k = 0,然后在更改k的值之前调用了n.get(k - 1)。索引值-1在ArrayList中超出范围,因此自然会出现异常。

Java不允许您同时返回多个值。返回多个值的一种方法是创建一个将您的值作为字段的对象,然后返回该对象(explanation here)。

© www.soinside.com 2019 - 2024. All rights reserved.