如何在单个数组中存储数组

时间:2010-04-02 12:01:53

标签: java arrays

如何将数组存储在单个数组中? 例如我有四个不同的数组,我想将它存储在单个数组int storeAllArray []中,当我调用时,例如storeAllArray [1],我将得到此输出[11,65,4,3,2,9,7]而不是单个元素?

int array1 [] = {1,2,3,4,5,100,200,400}; 
int array2 [] = {2,6,5,7,2,5,10};
int array3 [] = {11,65,4,3,2,9,7};
int array4 [] = {111,33,22,55,77};

int storeAllArray [] = {array1,array2,array3,array2} //我希望将所有数组存储在数组

for (int i=0; i<storeAllArray; i++){
   System.out.println(storeAllArray.get[0]); // e.g. will produce --> 1,2,3,4,5,100,200,400 , how can I do this?
}

EDITED: 我怎样才能获得这样的输出?

   System.out.println(storeAllArray [0])  --> [1,2,3,4,5,100,200,400]; 
    System.out.println(storeAllArray [1])  --> [2,6,5,7,2,5,10];
    System.out.println(storeAllArray [2])  --> [11,65,4,3,2,9,7];
    System.out.println(storeAllArray [2])  --> [111,33,22,55,77];

7 个答案:

答案 0 :(得分:8)

int array1 [] = {1,2,3,4,5,100,200,400};
int array2 [] = {2,6,5,7,2,5,10};
int array3 [] = {11,65,4,3,2,9,7};
int array4 [] = {111,33,22,55,77};
int[] storeAllArray [] = {array1,array2,array3,array4};

for (int[] array : storeAllArray) {
    System.out.println(Arrays.toString(array));
}

在Java 5及以上版本中,打印

[1, 2, 3, 4, 5, 100, 200, 400]
[2, 6, 5, 7, 2, 5, 10]
[11, 65, 4, 3, 2, 9, 7]
[111, 33, 22, 55, 77]

在Java 5之前,您应该使用

    System.out.println(Arrays.asList(array));

答案 1 :(得分:1)

如果我理解你的问题,你想把这些数组“扁平”到一个数组。在Java和其他语言中查看rosettacode.org这样的示例。

答案 2 :(得分:1)

int array1[] = { 1, 2, 3, 4, 5, 100, 200, 400 };
    int array2[] = { 2, 6, 5, 7, 2, 5, 10 };
    int array3[] = { 11, 65, 4, 3, 2, 9, 7 };
    int array4[] = { 111, 33, 22, 55, 77 };

    int[][] storeAllArray = new int[][] { array1, array2, array3, array2 };

    for (int j : storeAllArray[0]) {
        System.out.print(j + ", ");
    }

答案 3 :(得分:0)

使用以下语法

int[][] storeAllArray = {array1, array2, array3, array4};

答案 4 :(得分:0)

要访问所选数组的单个元素,您需要执行以下操作:

storeAllArray[i][j]

答案 5 :(得分:0)

创建数组数组:

    int[] array1 = {1,2,3,4,5,100,200,400}; 
    int[] array2 = {2,6,5,7,2,5,10};
    int[] array3 = {11,65,4,3,2,9,7};
    int[] array4 = {111,33,22,55,77};

    int[][] allArrays = { 
        array1, array2, array3, array4
    };

    System.out.println(java.util.Arrays.toString(allArrays[0]));
    // prints "[1, 2, 3, 4, 5, 100, 200, 400]"

答案 6 :(得分:-1)

There is no need to do so. You can use a two dimensional array for the job. Make sure the row length should be equal to the array with max length.

    int a[]={1,2,3,4,5,6};
    int b[]={4,8,3,6,4,5};
    int c[][]=new int[2][6];//here 2 refers to the no. of arrays and 6 refers to number of elements in each array