1

I'm having difficulties understanding why once i declare a multidimensional array like :

int t2[][] = new int[5][10] ;

I can still change the length of the arrays like so :

t2[0] = new int[12];

I thought once we declare the array to be a certain length we can't change it. So how is it possible here ?

2
  • You can do this with a single dimension too: int[] t = new int[5]; t = new int[12];. Commented Nov 18, 2017 at 12:55
  • You're simply not changing the array. Instead, you are creating a new array, with a new length. Commented Nov 18, 2017 at 12:56

1 Answer 1

5

Fundamentally speaking, a two-dimensional array is nothing more than an array of arrays. So this:

int t2[][] = new int[5][10] ;

is really doing this:

int t2[][] = new int[5][];
for (int i = 0; i < t2.length; i++)
{
    t2[i] = new int[10];
}

Thus in reality, you can assign t2[x] in the same way as you're assigning any other array element.

NOTE: You are not extending the length of the array by saying t2[0] = new int[12]. You are creating a new one, which means that if you have done any assignments to t2[0][x], then they will be lost unless you copy them over yourself.

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.