1

I have the following code which seems to compile:

int[] arr = {1, 2};
int[][] arr2 = {arr, {1, 2}, arr};
int[][][] arr3 = {arr2};

Could you please explain why the last statement works? Don't we assign a two-dimensional array to a three-dimensional array here?

Thanks

1 Answer 1

2

Don't we assign a two-dimensional array to a three-dimensional array here?

You are correct if you do this

   int[][][] arr3 = arr2;

But what you are doing here int[][][] arr3 = {arr2}; is not assigning. You are creating array with an element inside it.

Adding an element and assigning the references are 2 different things.

That works because in your array called arr3 you have a 2D array at row zero and column zero which is fine.

Inshort

int[][][] arr3 = {arr2};

is equals to

int[][][] arr3 = new int[10][10][10];
arr3[0] = arr2;
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.