Java如何轻松地将多维数组转换为单个数组?

时间:2013-12-19 16:15:28

标签: java

[[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]]

如何将其转换为:

[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]

有一种简单的方法吗?

4 个答案:

答案 0 :(得分:2)

ArrayUtils.addAll(array1,array2)

答案 1 :(得分:1)

您可以创建一个新数组并使用for循环手动填充,如下所示:

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]);
    }
}

答案 2 :(得分:1)

这样做

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()]);

答案 3 :(得分:0)

我会使用嵌套的for循环:

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);

}