开发者

How to store arrays in single array

How can I store arrays in single array? e.g. I have four different arrays, I want to store it in single array int storeAllArray [] and when I call e.g. storeAllArray[1] , I will get this output [11,65,4,3,2,9,7]instead of single elements?

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} // I want store all array in on array

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: How can I get output like this?

   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])  --> [1开发者_JAVA百科11,33,22,55,77];


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

In Java 5 and above, this prints

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

Prior to Java 5, you should use

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


If I understand your question, you want to "flatten" those arrays to one array. Look at rosettacode.org for such example in Java and other languages.


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 + ", ");
    }


To access a single element of the selected array you need to do something like:

storeAllArray[i][j]


use the following syntax

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


Create array-of-arrays:

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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜