You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java二维数组左拼接、顶部拼接低开销方法及相关工具库求推荐

Java二维数组水平/垂直拼接高性能实现方案

核心实现(JDK内置方法,无额外依赖)

你需要的两种拼接操作完全可以用JDK内置的System.arraycopy()实现,这个方法是native级别的底层内存拷贝实现,不会额外遍历数组,计算开销极低,内存占用仅等于最终结果数组的占用量,完全满足你的要求。

1. 水平拼接(将B数组拼到A数组左侧)

/**
 * 水平拼接两个二维数组,将leftArray拼到rightArray的左侧
 * 要求两个数组行数相同
 */
public static int[][] horizontalMerge(int[][] leftArray, int[][] rightArray) {
    // 参数校验
    if (leftArray == null || leftArray.length == 0) return rightArray;
    if (rightArray == null || rightArray.length == 0) return leftArray;
    if (leftArray.length != rightArray.length) {
        throw new IllegalArgumentException("两个数组行数必须一致");
    }
    int rows = leftArray.length;
    int[][] result = new int[rows][];
    for (int i = 0; i < rows; i++) {
        int leftLen = leftArray[i].length;
        int rightLen = rightArray[i].length;
        result[i] = new int[leftLen + rightLen];
        // 拷贝左侧数组行
        System.arraycopy(leftArray[i], 0, result[i], 0, leftLen);
        // 拷贝右侧数组行
        System.arraycopy(rightArray[i], 0, result[i], leftLen, rightLen);
    }
    return result;
}

调用示例:int[][] combinedArray = horizontalMerge(otherArray, array);,即可得到左侧拼接的结果。

2. 垂直拼接(将topArray拼到bottomArray的顶部)

/**
 * 垂直拼接两个二维数组,将topArray拼到底部数组的上方
 * 要求两个数组的列数相同
 */
public static int[][] verticalMerge(int[][] topArray, int[][] bottomArray) {
    if (topArray == null || topArray.length == 0) return bottomArray;
    if (bottomArray == null || bottomArray.length == 0) return topArray;
    if (topArray[0].length != bottomArray[0].length) {
        throw new IllegalArgumentException("两个数组列数必须一致");
    }
    int topRows = topArray.length;
    int bottomRows = bottomArray.length;
    int[][] result = new int[topRows + bottomRows][];
    // 拷贝顶部所有行
    System.arraycopy(topArray, 0, result, 0, topRows);
    // 拷贝底部所有行
    System.arraycopy(bottomArray, 0, result, topRows, bottomRows);
    return result;
}

调用示例:int[][] finalCombinedArray = verticalMerge(otherCombinedArray, combinedArray);,即可得到最终拼接结果。

性能与内存说明

  • System.arraycopy是JDK内置的native方法,底层直接操作内存块拷贝,没有Java层的遍历开销,性能是Java语言内能达到的最优水平
  • 内存仅占用最终结果数组的大小,按int占4字节计算,80MB的内存限制可以支持最大20971520个int元素,对应比如5000行*4000列的二维数组,完全满足游戏位置缓存的使用需求
  • 不需要引入任何第三方依赖,兼容性最好

如果项目已经引入了Apache Commons Lang库,也可以用ArrayUtils.addAll()方法实现,底层本质是封装了System.arraycopy,性能和上述原生实现没有差异。

内容的提问来源于stack exchange,提问作者Day Trip

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 09:24:05