[英]Auto-generate variable size 2D array from 1D arrays
我正在尋找有關如何創建一種基於兩個參數生成2D數組的方法的建議,整數s決定2D數組的行數,而int x []將是長度為20的不同1D數組的位置將填充2D數組的每一行。 到目前為止,這是我想出的方法,但是它只用0s填充每一行,只有一行用輸入數組填充。 我基本上需要用一堆相同大小的1D數組填充自動生成的2D數組的每一行。 請幫忙。 謝謝 !
public class c {
public int [][] f;
public int [][] a(int x[], int s){
f = new int [s][20];
for(int j = 0; j < x.length; j++) {
f[s-1][j] = x[j];
}
return f;
}
public void d(){
for (int i =0; i < f.length; i++) {
for(int j = 0; j < f[i].length; j++) {
System.out.print(f[i][j] + " ");
}
System.out.println(" ");
}
}
}
我可以看到,您所需要做的就是創建具有給定行數的2D數組,並將給定的1D數組復制到的每一行中。 這很簡單:
例:
public static int[][] createArray(int[] arr, int totalRows) {
int[][] res = new int[totalRows][arr.length];
for (int row = 0; row < totalRows; row++)
System.arraycopy(arr, 0, res[row], 0, res[row].length);
return res;
}
這可以使用Java中的流api來實現
int[][] arrInt = { { 1, 2 }, { 3, 4, 5 } };
int result[] = Arrays.stream(arrInt).flatMapToInt(Arrays::stream).toArray();
System.out.println(Arrays.toString(result));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.