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



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

我想要合并的数组是一些类似于text='hello','hello'的行。retweets='2,5'和geo='19912299293'。

并且应该导致:-

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

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

感谢您的回复。

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];
}
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数组中。

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

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

注意:可以更改类型,可能会为其他D多次调用2个Darray。

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

相关内容

  • 没有找到相关文章