简体   繁体   English

不使用ArrayList将2D数组转换为1D Array

[英]Converting 2D array to 1D Array without using ArrayList

Create Function for Convert 2d array into 1D array 创建将2d数组转换为1D数组的函数

But at Declaration time the size of 1D array how to give size to the new 1D array 但是在声明时,一维数组的大小如何为新一维数组赋予大小

int[] convert(int[][] input){
    int[] result;
    int z=0;
    for(int row=0;row<input.length;row++) {
        for(int col=0;col<input[row].length;col++) {
            result[z]=input[row][col];
            z++;
        }
    }
    return result;/* Error comes here For Initialization. How to initialize before Knowing size*/
}

if rows and columns are balanced 行和列是否平衡

int result[] = new int[input.length * input[0].length];

otherwise, you have to loop through the whole array while keeping a count of length 否则,您必须遍历整个数组,同时保持长度计数

int len = 0;
for(int[] a : input){
    len+=a.length;
}
int[] result = new int[len];

您可以通过这种方式简单地计算大小(即数* 列数 ):

int[] result = new int[input.length * input[0].length] ;

1)If it is rectangular 2D array, compute the size this way 1)如果是矩形2D数组,则以这种方式计算大小

int array[]  = new int[input.length * input[0].length];

2)If it is not rectangular, iterate through each row and add the length of each sub-array 2)如果不是矩形,则遍历每一行并添加每个子数组的长度

int size = 0;
for(int i=0;i<input.length;i++){
 size += input[i].length;
}

Or you could just use streams with out to have to take care of size by yourself: 或者您可以只使用流而不必自己照顾大小:

int[] convert(int[][] input){    
    return Stream.of(input).flatMapToInt(x -> Arrays.stream(x)).toArray();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM