从2D double [] []数组中获取子数组

时间:2017-02-12 22:24:20

标签: java

我正在尝试从double[][] 3x3矩阵中获取子数组(以计算行列式)。我一直得到ArrayIndexOutOfBoundsException

知道为什么吗?

public double[][] get2DSubArray(double[][] largeArray, int rowStartIndex, int rowEndIndex, int columnStartIndex, int columnEndIndex) {
    double[][] subArray = new double[rowEndIndex-rowStartIndex+1][columnEndIndex-columnStartIndex+1];
    for (int row = rowStartIndex; row < rowEndIndex; row++) {
        subArray[row] = Arrays.copyOfRange(largeArray[row], columnStartIndex, columnEndIndex);
    }
    return subArray;
}

2 个答案:

答案 0 :(得分:1)

如果行开始为500且结束为505,则for循环中的变量将从500而不是0开始。您想要将“subArray [row] =”替换为“subArray [row-rowStartIndex] =” 。您正在引用较大阵列中的位置,而副本将位于较小阵列中。

编辑:

//固定版本:

public static double[][] get2DSubArray(double[][] largeArray, int rowStartIndex, int rowEndIndex, int columnStartIndex,
            int columnEndIndex) {
        double[][] subArray = new double[rowEndIndex - rowStartIndex + 1][columnEndIndex - columnStartIndex + 1];
        for (int row = rowStartIndex; row <= rowEndIndex; row++) {
            subArray[row-rowStartIndex] = Arrays.copyOfRange(largeArray[row], columnStartIndex, columnEndIndex+1);
        }
        return subArray;
    }

答案 1 :(得分:1)

看起来它与数组初始化有关,传递给方法的array似乎不是3x3。例如,以下不会产生异常:

public static void main(String[] args) throws IOException {
    double[][] array = new double[][]{{1d,1d,1d},{2d,2d,2d},{3d,3d,3d}};
    double[][] subArray = get2DSubArray(array, 1, 2, 1, 2);
    for(double[] arrayElement : subArray){
        for(double number : arrayElement){
            System.out.println(number);
        }
    }
}

public static double[][] get2DSubArray(double[][] largeArray, int rowStartIndex, int rowEndIndex, int columnStartIndex,
        int columnEndIndex) {
    double[][] subArray = new double[rowEndIndex - rowStartIndex + 1][columnEndIndex - columnStartIndex + 1];
    for (int row = rowStartIndex; row < rowEndIndex; row++) {
        subArray[row] = Arrays.copyOfRange(largeArray[row], columnStartIndex, columnEndIndex);
    }
    return subArray;
}

<强>更新

虽然上述解决方案不会产生异常,但它也不会产生正确的输出。主要是由于以下原因:

  • Arrays.copyOfRange方法的第三个参数是独占的,因此我们必须通过columnEndIndex+1才能使其工作
  • for循环仅对提供的​​参数集执行一次,而它应至少执行两次
  • 我们需要将其分配给Arrays.copyOfRange
  • ,而不是将subArray[row]分配给subArray[<zero based index>]

以下解决方案确实有效:

public double[][] get2DSubArray(double[][] largeArray, int rowStartIndex, int rowEndIndex, int columnStartIndex,
        int columnEndIndex) {
    double[][] subArray = new double[rowEndIndex - rowStartIndex + 1][columnEndIndex - columnStartIndex + 1];
    int index = 0;
    for (int row = rowStartIndex; row <= rowEndIndex; row++) {
        subArray[index++] = Arrays.copyOfRange(largeArray[row], columnStartIndex, columnEndIndex+1);
    }
    return subArray;
}