-1

I want to copy the old array to the new one and I want to add the empty elements to the new array

import java.util.Arrays;

public class testArray2D {

    public static void main(String[] args) {
        int[][] a = {{1, 2, 3}};
        // make a one bigger
        int add = 3;
        a = Arrays.copyOf(a, a.length + add);
        for (int i = 1; i < a.length; i++) {
            for (int j = 0; j < a[i].length; j++) {
                a[i][j] = 1;
            }
        }
        for (int i[] : a) {
            System.out.println(Arrays.toString(i));
        }
    }
}

The expected output is

1 2 3
1 1 1 
1 1 1
1 1 1

Why I can't run this?

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
  • 2
    What type of error do you get? – Steyrix Dec 10 '19 at 11:07
  • be curious, print the array just after the `copyOf` (or use a debugger to see its content) (hint there is no *real* 2D array in java, its an array of arrays) – user85421 Dec 10 '19 at 11:09
  • `Arrays.copyOf` will pad with nulls, not with repeated instances of whatever was at 0-th slot. – Amadan Dec 10 '19 at 11:10
  • Does it compile? If it does, [debugging](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems?noredirect=1&lq=1) will give you the answer. – Curiosa Globunznik Dec 10 '19 at 11:10

2 Answers2

1

You need to initialize the new array elements.

import java.util.Arrays;

public class testArray2D {

    public static void main(String[] args) {
        int[][] a = {{1, 2, 3}};
        // make a one bigger
        int add = 3;
        a = Arrays.copyOf(a, a.length + add);
        for (int i = 1; i < a.length; ++i) {
            if(a[i] == null) {
                a[i] = new int[3];
            }
            for (int j = 0; j < a[i].length; ++j) {
                a[i][j] = 1;
            }
        }
        for (int i[] : a) {
            System.out.println(Arrays.toString(i));
        }
    }
}
Adder
  • 5,708
  • 1
  • 28
  • 56
1

If you want to copy existing array to a new array having size larger than the existing array, I would suggest the following.

int[][] source_arr = {{1, 2, 3}};
int add = 3;
int[][] dest_arr = new int[source_arr[0].length+add][source_arr[0].length];
for (int i = 0; i < source_arr.length; i++) {
    System.arraycopy(source_arr[i], 0, dest_arr [i], 0, source_arr[i].length);
}