将数组转换为多维数组 - Java

时间:2013-02-05 14:27:03

标签: java arrays loops for-loop multidimensional-array

有没有办法将三个单维数组转换为多维数组。 例如,我有三个数组(文本,转发,地理)我如何合并它们,因此它显示为: -

我要合并的数组是text ='hello,'hello'。转推='2,5'和geo ='19912,9929293'。

应该导致: -

combined = 
[hello, 2, 19912
hello, 5, 929293]

等等......所有阵列的大小都相同。我知道我应该以某种方式在for循环中循环,但我不太确定如何实现它。

感谢您的回复。

4 个答案:

答案 0 :(得分:2)

int count = ...;

String [] text = new String [count];
int [] retweets = new int [count];
int [] geo = new int [count];

// Fill arrays with data here

Object [] combined = new Object [count * 3];

for (int i = 0, j = 0; i < count; i++)
{
    combined [j++] = text [i];
    combined [j++] = retweets [i];
    combined [j++] = geo [i];
}

答案 1 :(得分:1)

public static void main(String[] args) {

    String[] array1 = { "hello1", "A2", "X19912" };
    String[] array2 = { "hello2", "B2", "Y19912" };
    String[] array3 = { "hello3", "C2", "Z19912" };
    String[] copyArrays = new String[array1.length + array2.length
            + array3.length];
    System.arraycopy(array1, 0, copyArrays, 0, array1.length);
    System.arraycopy(array2, 0, copyArrays, array1.length, array2.length);
    System.arraycopy(array3, 0, copyArrays, array1.length + array2.length,
            array3.length);

    String[][] array = new String[3][3];
    int index = 0;
    for (int i = 0; i < array.length; i++)
        for (int j = 0; j < array[i].length; j++) {
            array[i][j] = copyArrays[index++];
        }

    for (int i = 0; i < array.length; i++) {
        for (int j = 0; j < array[i].length; j++) {

            System.out.print(array[i][j] + "  ");
        }
        System.out.println();
    }
}

输出:

hello1  A2  X19912  
hello2  B2  Y19912  
hello3  C2  Z19912 

此代码将首先将给定的数组复制到新数组中。然后它将使用for循环将copyArrays的所有元素插入到2d数组中。

答案 2 :(得分:1)

String[] text =...;
int[] retweets =...;
int[] geo =...;

int len = text.length;

List<List<Object>> items = new ArrayList<>();
for (int i = 0; i < len; i++) {
   List<Object> item = new ArrayList<>();
   item.add(text[i]);
   item.add(retweets[i]);
   item.add(geo[i]);
   items.add(item);
}

答案 3 :(得分:0)

toTableFormTheArrays&#34;一种聪明的方式。是:

public static String[][] to2DArray(String[]... yourArrays){
    return yourArrays;
}

then the code is:
String[] text =  {"hello", "hello"};
String[] retweets = {2, 5};
String[] geo = {19912, 929293};

String[][] yourTableForm2DArray = to2DArray(text, retweets, geo);

注意:可以更改类型,多次调用to2darray以获取其他D,也许。