[英]Need help creating an array
我需要一些入门帮助。 我有一个存储多个数组的数组(在这种情况下,假设3,或多或少):
mainarray {arr, arr, arr}
mainarray中的所有数组都具有相同数量的值,但是这也可能更改为更少或更少。可以说我有以下数组:
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"}};
提前致谢!
干得好
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
该代码适用于所有大小的数组,但前提是它们的大小相同(如您所说)。
这只是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个红色
2两蓝
3三黄
输入:
Object arr1[] = { "1", "2", "3"};
Object arr2[] = { "One", "Two", "Three"};
Object arr3[] = { "Red", "Blue", "Yellow"};
输出:
1个红色
2两蓝
3三黄
4四绿
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.