有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java将数组添加到数组特殊模式

我正在用Java开发一个游戏,我需要缓存一些基于位置的信息。如果我有以下数组:

int[][] array = {
            {1, 2, 3},
            {1, 2, 3},
            {1, 2, 3}
    };

然后我有另一个数组:

int[][] otherArray = {
            {4, 5, 6},
            {4, 5, 6},
            {4, 5, 6}
    };

现在我想用一种特殊的方式把它们结合起来。我想在array的左边添加otherArray。因此,结果如下所示:

int[][] combinedArray = {
            {4, 5, 6, 1, 2, 3},
            {4, 5, 6, 1, 2, 3},
            {4, 5, 6, 1, 2, 3}
    };

然后我有另一个组合阵列:

int[][] otherCombinedArray = {
            {30, 17, 139, 65, 335, 99},
            {50, 43, 57, 53, 423, 534},
            {90, 67, 78, 24, 99, 67}
    };

现在我想将它添加到原始组合数组的顶部。因此,最终结果如下所示:

int[][] finalCombinedArray = {
            {30, 17, 139, 65, 335, 99},
            {50, 43, 57, 53, 423, 534},
            {90, 67, 78, 24, 99, 67},
            {4, 5, 6, 1, 2, 3},
            {4, 5, 6, 1, 2, 3},
            {4, 5, 6, 1, 2, 3}
    };

有人能告诉我一个好的库或内置的方法来做这件事吗?我还想指出,该方法的计算量不应该太大(比如多次遍历所有数组,并且不应该使用太多内存,比如80MB)

谢谢你的帮助


共 (1) 个答案

  1. # 1 楼答案

    Java本身不提供连接方法,但我们可以使用System.arraycopy(正如上面@user16320675所建议的)

    使用System.arraycopy指定要复制的数组+目标数组->;有大小为10的数组A和大小为2的数组B,可以使用命令将B数组复制到A中

      int[] source = { 1,2,3,4,5 };
      int[] destination = new int[10];
    
      // You can play with the numbers below
      int COPY_AT_INDEX = 0;  // Start to copy at position destination[0]
      int AMOUNT_TO_COPY = 5; // Copying from 0 to source.length
    
      System.arraycopy(source, 0, destination, COPY_AT_INDEX, AMOUNT_TO_COPY);
    
      System.out.println(Arrays.toString(source));  // [1, 2, 3, 4, 5]
      System.out.println(Arrays.toString(destination));  // [1, 2, 3, 4, 5, 0, 0, 0, 0, 0]
    

    现在,如果我们使用arraycopy,似乎您必须确定何时作为行复制,何时作为列复制

    // Assuming a[][] and b[][] have the same size.
    public int[][] mergeAsColumns(int[][] a, int[][] b) {
        int rows = a.length;
        int columns = a[0].length;
    
        int[][] merged = new int[rows][2 * columns];
    
        for (int i = 0; i < a.length; i++) {
            System.arraycopy(a[i], 0, merged[i], 0, columns);
            System.arraycopy(b[i], 0, merged[i], rows, columns);
        }
    
        return merged;
    }
    

    合并为行与另一行类似,但会更改要影响的位置以及创建合并数组的方式

    // Assuming a[][] and b[][] have the same size.
    public int[][] mergeAsRows(int[][] a, int[][] b) {
        int rows = a.length;
        int columns = a[0].length;
    
        int[][] merged = new int[2 * rows][columns];
    
        for (int i = 0; i < rows; i++) {
            System.arraycopy(a[i], 0, merged[i], 0, columns);
            System.arraycopy(b[i], 0, merged[rows + i], 0, columns);
        }
    
        return merged;
    }