【问题标题】:Append two 2D arrays without use of the Java arrays class在不使用 Java 数组类的情况下附加两个 2D 数组
【发布时间】:2016-03-02 21:33:57
【问题描述】:

我很困惑如何在不使用/导入数组类的情况下创建一个 java 方法来附加两个不同的二维数组。这是我目前所拥有的:

private Cell[][] appendArrays(Cell[][] first, Cell[][] second) {
    Cell[][] third = new Cell[first.length][first[0].length + second[0].length];

    for (int i = 0; i < first.length; i++) {
        for (int j = 0; j < first[i].length; j++) {
            third[i][j] = first[i][j];
        }
    }
    for (int i = 0; i < second.length; i++) {
        for (int j = 0; j < second[i].length; j++) {
            // don't know what to do here
        }
    }
    return third;
}

Cell 只是一个对象,但我试图了解附加数组背后的逻辑,因此我们将不胜感激!

另外,我知道在这里找到了一个类似的问题 (How do you append two 2D array in java properly?),但答案是在从上到下附加数组时给出的(假设两个参数数组具有相同数量的列),而我正在寻找左右追加数组(假设两个参数数组的行数相同)。

【问题讨论】:

  • third[i][first[0].length + j] = second[i][j];
  • 类似third[ first.length + i ][ first[0].length + j ] = second[i][j]?您还假设所有Xfirst[X].length 相同(second[X] 也相同)。

标签: java arrays append concatenation cell


【解决方案1】:

你快到了。我认为您正在寻找这样的东西。

private Cell[][] appendArrays(Cell[][] first, Cell[][] second) {
    Cell[][] third = new Cell[first.length][first[0].length + second[0].length];

    for (int i = 0; i < first.length; i++) {
        for (int j = 0; j < first[i].length; j++) {
            third[i][j] = first[i][j];
        }
        for (int j = first[i].length; j < first[i].length + second[i].length; j++) {
            third[i][j] = second[i][j-first[i].length];
        }
    }
    return third;
}

【讨论】:

    猜你喜欢
    • 2021-04-21
    • 2023-03-17
    • 2011-01-11
    • 1970-01-01
    • 2020-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-14
    相关资源
    最近更新 更多