分为A维数组,反之亦然Java的转换一个二维数组(数字) [英] Converting a Bidimensional Array (Numbers) Into A Dimensional Array and Viceversa on Java
本文介绍了分为A维数组,反之亦然Java的转换一个二维数组(数字)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要帮助的现在。我需要数2维数组转换为Java中一维阵列。谁能帮我?
I'm in need of help right now. I need to convert 2 dimensional array of numbers to a one dimensional array in Java. Can anyone help me?
推荐答案
你的意思是这样的?
import java.util.*;
public class Test
{
public static void main(String[] args)
{
String[][] data = new String[][]
{
{ "Foo", "Bar" },
{ "A", "B" }
};
String[] flattened = flatten(data);
for (String x : flattened)
{
System.out.println(x);
}
}
public static <T> T[] flatten(T[][] source)
{
int size = 0;
for (int i=0; i < source.length; i++)
{
size += source[i].length;
}
// Use the first subarray to create the new big one
T[] ret = Arrays.copyOf(source[0], size);
int index = source[0].length;
for (int i=1; i < source.length; i++)
{
System.arraycopy(source[i], 0, ret, index, source[i].length);
index += source[i].length;
}
return ret;
}
}
如果您想为基本类型,你必须写为每个原始类型的过载,但你可以使用新INT [大小]
而不是 Arrays.copyOf
在这一点上。
If you want it for primitive types, you'll have to write an overload for each primitive type, but you can use new int[size]
instead of Arrays.copyOf
at that point.
这篇关于分为A维数组,反之亦然Java的转换一个二维数组(数字)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文