Java how to convert a multidimensional array to single array easily?
本问题已经有最佳答案,请猛点这里访问。
1 2 | [[4, 17, 28, 38, 43, 58, 69, 77, 83], [4, 12, 24, 35, 48, 55, 62, 73, 87], [11, 15, 22, 36, 46, 60, 67, 80, 84]] |
如何将其转换为:
1 2 | [4, 17, 28, 38, 43, 58, 69, 77, 83, 4, 12, 24, 35, 48, 55, 62, 73, 87, 11, 15, 22, 36, 46, 60, 67, 80, 84] |
有简单的方法吗?
1 | ArrayUtils.addAll(array1,array2) |
这样做
1 2 3 4 5 6 | Integer td[][]= {{4, 17, 28, 38, 43, 58, 69, 77, 83}, {4, 12, 24, 35, 48, 55, 62, 73, 87}, {11,15, 22, 36, 46, 60, 67, 80, 84}}; List<Integer> singleDArray = new ArrayList<Integer>(); for (Integer[] array :td) { singleDArray.addAll(Arrays.asList(array)); } Integer[] sd = singleDArray.toArray(new Integer[singleDArray.size()]); |
您可以创建一个新数组并使用for循环手动填充它,如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 | int[][] numbers = {{4, 5, 6},{3, 1, 10}, {4, 2, 9}}; ArrayList<Integer> numbers1Dim = new ArrayList<Integer>(); for (int i = 0; i < numbers.length; i++) { for (int x = 0; x < numbers[i].length; x++) { numbers1Dim.add(numbers[i][x]); } } |
我将使用嵌套的for循环:
1 2 3 4 5 6 7 8 9 | Integer[][] array = <your array>; List resultList = new ArrayList(); for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[i].length; j++) { resultList.add(array[i][j]); } } Integer[] resultArrayList = resultList.toArray(new Integer[resultList.size()]); System.out.println(resultArrayList); |
}