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.

3
  • You should prefer using ArrayList if you need dynamism in size, although arrays perform better than ArrayList Commented Oct 12, 2018 at 6:51
  • Possible duplicate of How to make an array of arrays in Java Commented Oct 12, 2018 at 7:24
  • I'd checked that before posting the question, it's not. Commented Oct 12, 2018 at 10:27

1 Answer 1

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];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.