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

如何将Java二维数组的元素转换为新的一维数组并返回?

解决Java二维数组转一维数组时元素重复的问题

问题根源

你的代码存在三个核心问题:

  • 循环逻辑错误:外层for (int i = 0; i < 7; i++)会重复遍历整个二维数组,每次遍历完所有元素后,nA[i]会被二维数组的最后一个元素(10)覆盖,最终所有位置都被赋值为10。
  • 数组长度固定:nA被硬编码为长度10,无法适配元素数量变化的二维数组。
  • 下标管理混乱:没有用独立变量跟踪一维数组的赋值位置,而是依赖外层循环的i,导致重复覆盖。

修正方案

  1. 先计算二维数组的总元素个数,动态初始化一维数组长度。
  2. 使用独立下标变量跟踪一维数组的当前赋值位置,遍历二维数组的每个元素时依次赋值,下标自增。

修正后的完整代码

public class MyClass {

    public static int[] collect(int[][] array) {
        // 计算二维数组的总元素数
        int totalElements = 0;
        for (int[] subArray : array) {
            totalElements += subArray.length;
        }
        
        int[] nA = new int[totalElements];
        int currentIndex = 0;
        
        // 遍历二维数组,逐个赋值到一维数组
        for (int[] subArray : array) {
            for (int num : subArray) {
                nA[currentIndex++] = num;
            }
        }
        
        return nA;
    }

    public static void main(String args[]) {
        int[][] array = {{1}, {2,3}, {4,5,6}, {7}, {}, {}, {8,9,10}};
        int[] z = collect(array);
        
        for (int x : z) {
            System.out.print(x + " ");
        }
    }
}

运行结果

执行后会输出:1 2 3 4 5 6 7 8 9 10 ,完全符合将二维数组所有元素按顺序转为一维数组的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 23:10:30