Skip to content
Advertisement

How to create an new one dimensional array with elements of a 2d array and return it?

I need tp create a new array with the elements of a 2d array in java. However, it only adds the last number of the 2d array which results in an array of the same value.

public class MyClass {

public static int[] collect(int[][] array) {
    int[] nA = new int[10];

    for (int i = 0; i < 7; i++) {

        for (int[] y : array) {

            for (int x : y) {

                nA[i] = x;

            }

        }
    }
    
    return nA;
}

public static void main(String args[]){

    int[][] array = {{1}, {2,3}, {4,5,6}, {7}, {}, {}, {8,9,10}};

    int[] z = collect(array);

    for (int x : z) {
        System.out.print(x +  " ");
    }}
}

Advertisement

Answer

You have an outer loop for (int i = 0; i < 7; i++) that is causing the issues.

The value of “i” does not change and the whole array is traversed ‘7‘ times and the last element is persisted at the index specified by ‘i‘. And the whole thing repeats for “i+1“. Ultimately what is printed is the last element of the last sub-array multiple times. That is not what you want.

Please look at the following code. Note, we also get the length of the array dynamically from the argument (never hardcode for you would like your method to be suitable for all sizes).

public static int[] collect(int[][] array) {

    // calculate length
    int length = 0;
    for (int a[] : array) {
        length += a.length;
    }

    int[] nA = new int[length];

    // for (int i = 0; i < 7; i++) {
        int i=0;
        for (int[] y : array) {

            for (int x : y) {

                nA[i++] = x;
            }
        }
    // }

    return nA;
}

public static void main(String args[]) {

    int[][] array = {{1}, {2, 3}, {4, 5, 6}, {7}, {}, {}, {8, 9, 10}, {11}};

    int[] z = collect(array);

    for (int x : z) {
        System.out.print(x + " ");
    }
}

Prints:

1 2 3 4 5 6 7 8 9 10 11 
2 People found this is helpful
Advertisement