views:

175

answers:

6

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])  --> [111,33,22,55,77];
+1  A: 

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.

Michał Niklas
A: 

use the following syntax

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

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

storeAllArray[i][j]
Seth M.
+1  A: 
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 + ", ");
    }
Robert
A: 

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]"
polygenelubricants
+4  A: 
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));
Péter Török
Thank you Peter :-)
Jessy
@Jessy Have you by any chance tried to use `Arrays.asList(array)` with Java 5 or above? That won't work - use `Arrays.toString(array)` instead.
Péter Török