将数组分配给对象数组时出错

时间:2019-04-01 04:11:12

标签: java arrays

我正在尝试在循环内为对象数组的元素分配一个float数组。前几行完成此任务没有任何问题,但是变量FData突出显示,并显示以下消息:The type of the expression must be an array type but it resolved to Object。尽管在互联网上进行搜索,但我仍然不知道是什么原因导致了错误。

private void newData(int nF, int nL, int[] nN) {
    Object[] I = new Object[4], W = I, A = I, FError = I, FData = new Object[3];
    I[0] = new float[1052][1052]; I[1] = new float[nF][185][185]; I[2] = new float[nF][nF][34][34]; I[3] = new float[nF][nF][nF][6][6];
    W[0] = new float[nF][128][128]; W[1] = new float[nF][nF][16][16]; W[2] = new float[nF][nF][nF][5][5]; W[3] = new float[nF][nF][nF][nF][6][6];
    A[0] = new float[nF][925][925]; A[1] = new float[nF][nF][170][170]; A[2] = new float[nF][nF][nF][30][30]; A[3] = new float[nF][nF][nF][nF];
    FData[0] = new Object[nL - 1]; FData[1] = new Object[nL]; FData[2] = FData[0];
    for(int i = 0; i < nL; i++) {
        FData[1][i] = new float[nN[i]];
        if (i > 0) FData[0][i - 1] = FData[1][i];
        FData[2][i] = new Float[nN[i]][nN[i] * nN[i + 1]];
    }
    FError[0] = FData[0]; FError[1] = FError[0]; FError[2] = FError[0]; FError[3] = FData[2];
}

2 个答案:

答案 0 :(得分:0)

Object[] FData = new Object[3];

FData是一维数组。这些访问权限很好:

FData[0] = ...;
FData[1] = ...;
FData[2] = ...;

这些二维访问不是:

FData[1][i] = ...;
FData[2][i] = ...;

FData[1]的编译时类型为Object。编译器不知道或不在乎您是否已为该插槽分配了子数组Object[]。编译时类型为Object,并且不能在[]上使用Object

答案 1 :(得分:0)

我通过创建一些虚拟数组并将循环的结果添加到FData来解决了这个问题。

private void newData(int nF, int nL, int[] nN) throws IOException {
    Object[] I = new Object[4], W = I, A = I, FError = I, FData = new Object[3], t0 = new Object[nL], t1 = t0, t2 = t0;
    I[0] = new float[1052][1052]; I[1] = new float[nF][185][185]; I[2] = new float[nF][nF][34][34]; I[3] = new float[nF][nF][nF][6][6];
    W[0] = new float[nF][128][128]; W[1] = new float[nF][nF][16][16]; W[2] = new float[nF][nF][nF][5][5]; W[3] = new float[nF][nF][nF][nF][6][6];
    A[0] = new float[nF][925][925]; A[1] = new float[nF][nF][170][170]; A[2] = new float[nF][nF][nF][30][30]; A[3] = new float[nF][nF][nF][nF];
    FData[0] = new Object[nL - 1]; FData[1] = new Object[nL]; FData[2] = FData[0];
    for(int i = 0; i < nL; i++) {
        t1[i] = new float[nN[i]];
        if (i > 0) {
            t0[i - 1] = t1[i];
            t2[i - 1] = new float[nN[i - 1]][nN[i - 1] * nN[i]];
        }
        else t2[i] = new float[nN[i]][nN[i] * nN[i + 1]];
    }
    FData[0] = t0; FData[1] = t1; FData[2] = t2;
    FError[0] = FData[0]; FError[1] = FError[0]; FError[2] = FError[0]; FError[3] = FData[2];
    save(new Object[] {I,W,A,FData,FError});
}