0

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

我要合并的数组类似于 text = 'hello, 'hello'。转推 = '2,5' 和地理 = '19912, 929293'。

并且应该导致:-

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

等等......所有的数组都是相同的大小。我知道我应该以某种方式循环 while 循环,但不太确定如何实现它。

感谢任何回应。

4

5 回答 5

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];
}
于 2013-02-05T14:30:56.313 回答
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);
}
于 2013-02-05T14:46:26.020 回答
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 loop 将 copyArrays 的所有元素插入到二维数组中。

于 2013-02-05T14:31:36.947 回答
1

“toTableFormTheArrays”的一个聪明方法是:

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 的多次调用,也许。

于 2016-01-18T03:20:03.523 回答
0
String[] text =  {"hello", "hello"};
int[] retweets = {2, 5};
int[] geo = {19912, 929293};

//create table of strings for each array
Object[][] combined = new Object[text.length][3];

//load information into table, converting all information into Strings
for(int row = 0; row<text.length; row++){
    combined[row][0] = text[row];
    combined[row][1] = retweets[row];
    combined[row][2] = geo[row];
}

这将创建一个应该如下所示的多维数组:

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

于 2015-05-02T02:40:36.460 回答