如何在 Java 中将多维数组映射到单一数组?
二维数组就是一维数组的数组。因此,将二维数组映射到一维数组。
创建等于二维数组长度的数组,然后使用 for 循环,逐行将二维数组的内容存储在上面创建的数组中。
示例
public class Mapping_2DTo1D { public static void main(String args[]) { int [][] array2D = {{7, 9, 8, 5}, {4, 5, 1, 8}, {9, 3, 2, 7}, {8, 1, 0, 9}}; int [] myArray1 = new int[array2D[0].length]; int [] myArray2 = new int[array2D[0].length]; int [] myArray3 = new int[array2D[0].length]; int [] myArray4 = new int[array2D[0].length]; for (int i = 0; i < array2D[0].length; ++i) { myArray1[i] = array2D[0][i]; myArray2[i] = array2D[1][i]; myArray3[i] = array2D[2][i]; myArray4[i] = array2D[3][i]; } System.out.println(Arrays.deepToString(array2D)); System.out.println(Arrays.toString(myArray1)); System.out.println(Arrays.toString(myArray2)); System.out.println(Arrays.toString(myArray3)); System.out.println(Arrays.toString(myArray4)); } }
输出
[[7, 9, 8, 5], [4, 5, 1, 8], [9, 3, 2, 7], [8, 1, 0, 9]] [7, 9, 8, 5] [4, 5, 1, 8] [9, 3, 2, 7] [8, 1, 0, 9]
广告