-
猛跑小猪
我可以提出这样的建议,String[][] my2Darr = {{5, 2, 3, 1}, {4, 2, 6, 9}, {8, 9, 1, 8}}; List<String> list = new ArrayList<>(); for(int i = 0; i < my2Darr.length; i++) { list.addAll(Arrays.asList(my2Darr[i])); // java.util.Arrays } String[] my1Darr = new String[list.size()]; my1Darr = list.toArray(my1Darr);爪哇 8:int[][] 2darr = {{5, 2, 3, 1}, {4, 2, 6, 9}, {8, 9, 1, 8}};int[] 1darr = Stream.of(2darr ).flatMapToInt(IntStream::of).toArray();System.out.println(Arrays.toString(1darr ));
-
杨__羊羊
int[][] twoDimensionalArray = {{5, 2, 3, 1}, {4, 2, 6, 9}, {8, 9, 1, 8}};int[] oneDimensionalArray = new int[twoDimensionalArray.length * twoDimensionalArray.length];for (int i = 0; i < twoDimensionalArray.length; i++) { for (int j = 0; j < twoDimensionalArray[0].length; j++) { oneDimensionalArray[i] = twoDimensionalArray[i][j]; }}您的解决方案几乎是正确的。您必须更正twoDimensionalArray.length为twoDimensionalArray[0].length. 因为你想水平和垂直迭代。如果您在 twoDimensionalArray.length 上迭代 2 次,您将迭代 2 倍水平轴的长度。
-
函数式编程
您可以使用它,它用于System.arraycopy()将内部数组复制到结果中:public static int[] flatten(int[][] input) { int length = input.length; if(length == 0) return new int[0]; int[] output = new int[length * input[0].length]; for(int i = 0; i < length; i++) { int[] inner = input[i]; // 1. Parameter: the source to copy from // 2. Parameter: the starting index from source // 3. Parameter: the destionation to copy to // 4. Parameter: the starting index from destination // 5. Parameter: the amount of elements to copy System.arraycopy(inner, 0, output, i * length, inner.length); } return output;}
-
慕田峪7331174
您可以使用 来执行此操作stream,例如:int[][] twoDimensionalArray = {{5, 2, 3, 1}, {4, 2, 6, 9}, {8, 9, 1, 8}};int[] oneDimensionalArray = Arrays.stream(twoDimensionalArray) .flatMapToInt(e -> Arrays.stream(e)) .toArray();System.out.println(Arrays.toString(oneDimensionalArray));