如何将二维数组展平为一维数组? [英] How to flatten 2D array to 1D array?

查看:44
本文介绍了如何将二维数组展平为一维数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将二维数组 int originalArray[][] 展平为一维数组?

How can I flatten the 2 dimensions array int originalArray[][] to 1 dimension array?

    int a [] = {1,2,6,7,2};
    int b [] = {2,44,55,2};
    int c [] = {2,44,511,33};

    int originalArray [][] = new int[][]{a,b,c};

推荐答案

一个简单的 for 循环就可以了,这并不困难,但取决于您想要复制值的顺序.例如(基于在您的示例中数组都具有相同长度的事实):

A simple for loop will do, it is not difficult, but will depend on the order in which you want to copy the values. For instance (based on the fact that in your example the arrays all have the same length):

int[] newArray = new int[3 * a.length];
int index = 0;
for (int n = 0; n < a.length; n++) {
    newArray[index++] = a[n];
    newArray[index++] = b[n];
    newArray[index++] = c[n];
}

或(不同的顺序,a、b、c可以是不同的长度):

or (different order, a, b, c can be of different lengths):

int[] newArray = new int[a.length + b.length + c.length];
System.arraycopy(a, 0, newArray, 0, a.length);
System.arraycopy(b, 0, newArray, a.length, b.length);
System.arraycopy(c, 0, newArray, a.length + b.length, c.length);

这篇关于如何将二维数组展平为一维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆