0

I want to dynamically allocate memory for an array of arrays, knowing that the number of rows is going to be n, but I don't want to allocate more memory for each row than needed, which is going to be i = 1:n, number of elements = i for each row, and I know this in advance.

    int [] a = new int[n];
    for (int i=0; i<n; i++)

I have just started to learn Java, and I'm new to this. As far as I know, the first line will allocate memory for n elements (number of rows), and what I want to do is create a new array of i elements at each iteration.

Lois2B
  • 111
  • 1
  • 16

1 Answers1

5

You can declare a two-dimensional array and allocate the first dimensional

  int [][] a = new int[n][];

And then, inside a loop, you can allocate the second one

 for (int i=0; i<n; i++)
   a[i] = new int[necessary_length];

But if you know the size in advance you obviously can declare it in the beginning

  int [][] a = new int[n][n];
dehasi
  • 2,644
  • 1
  • 19
  • 31