需要帮助创建一个数组

时间:2013-11-23 18:00:20

标签: java arrays object multidimensional-array jtable

我需要一些帮助才能入门。 我有一个存储多个数组的数组(在这种情况下,假设为3,这可能会更多或更少):

mainarray {arr, arr, arr}

主阵列中的所有数组都具有相同数量的值,但这也可能会更改为更少或更少 假设我有以下数组:

mainarray {
  arr{"1","2","3"};
  arr{"One","Two","Three"};
  arr{"Red","Blue","Yellow"};
}

每次我尝试制作这个Object [] []时,排序就像这样:

Object {{"1","2","3"}, {"One","Two","Three"}, {"Red","Blue","Yellow"}};

这是我的问题: 有没有办法让这个数组成为一个Object [] [],但这个排序呢?

Object {{"1","One","Red"}, {"2","Two","Blue"}, {"3","Three","Yellow"}};

提前致谢!

2 个答案:

答案 0 :(得分:2)

你去吧

    Object arr1[] = { "1", "2", "3" };
    Object arr2[] = { "One", "Two", "Three" };
    Object arr3[] = { "Red", "Blue", "Yellow" };
    //make an array of arrays
    Object allArr[] = { arr1, arr2, arr3 };
    //the new array to store values
    Object arr4[][] = new Object[3][3];

    for (int i = 0; i < 3; i++) {
        for (int j = 0, k = 0; j < 3 && k < 3; j++, k++) {
            //take the first array from array of arrays
            Object tmp[] = (Object[]) allArr[k];
            //take the ith element of each individual array and store in the new array in correct position 
            arr4[i][j] = tmp[i];

        }
    }
     //print the new array
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            System.out.print(arr4[i][j] + " ");
        }
        System.out.println();
    }

这适用于您的示例。你可以进一步概括它。

输出

1 One Red 
2 Two Blue 
3 Three Yellow 

答案 1 :(得分:2)

代码

此代码适用于所有大小的数组,假设它们的大小相同(如您所说) 这只是n1234代码的修改版本。

Object arr1[] = { "1", "2", "3"};
Object arr2[] = { "One", "Two", "Three"};
Object arr3[] = { "Red", "Blue", "Yellow"};

Object allArr[] = { arr1, arr2, arr3 }; // combination of the arrays

Object arr4[][] = new Object[arr1.length][allArr.length]; // array to be rearranged

// define the new, rearranged array
for (int i = 0; i < arr4.length; i++) {
    for (int j = 0, k = 0; j < arr4[i].length && k < arr4[i].length; j++, k++) 
    {
        Object tmp[] = (Object[]) allArr[k];
        arr4[i][j] = tmp[i];
    }
}       

// print the array
for (Object r[] : arr4) {
    for (Object c : r)
        System.out.print(c + " ");
    System.out.println("");
}

输入/输出

输入:

Object arr1[] = { "1", "2", "3", "4"};
Object arr2[] = { "One", "Two", "Three", "Four"};
Object arr3[] = { "Red", "Blue", "Yellow", "Green"};

输出:

  

1 One Red
  2两个蓝色
  3三黄


输入:

Object arr1[] = { "1", "2", "3"};
Object arr2[] = { "One", "Two", "Three"};
Object arr3[] = { "Red", "Blue", "Yellow"};

输出:

  

1 One Red
  2两个蓝色
  3三黄   4四绿

相关问题