5

Why does this code compile?

int[] array = new int[][]{{1}}[0];

On the left side is one-dimensional array. On the right I thougth that three-dimensional, but it is not?

3 Answers 3

7

The right side is a one dimensional array that is the first (0th) element of the two-dimensional array

new int[][]{{1}}

To show it out more clearly lets add parenthesis

int[] array = (new int[][]{{1}}) [0];// [0] is returning first row of 2D array
                          // which is 1D array so it can be assigned to `array` 
Sign up to request clarification or add additional context in comments.

4 Comments

int[][]{{1}} - I see two square brackets, so I suppose two-dimensional array. Why it is so? Could you explain more?
Now I understand. For those, who still do not see it: int array = new int[]{1, 2, 4} [0];. First the array is created with three elements and I choose first element from this. It is only int.
@Pawel - Glad you figured it out. I was starting to write up an explanation when your second comment popped up. It's a good thing, too--I was not doing a good job of it. :)
@Pshemo - The edit makes perfect sense, although I'm not sure exactly what OP's blind spot was. The key thing to realize is that new int[][]{{1}} (with or without parentheses around it) is an array creation expression and the trailing [0] is simply selecting the element at index 0 of the just-created array.
3

The right side expression does two things.

//   instantiate new 2D array
//            ┌──────┸───────┑  ┌ access zeroth element of new 2D array
//            │              │  │
int[] array = new int[][]{{1}} [0];

This is basically equivalent to the following:

int[][] array2D = new int[1][1];
array2D[0][0] = 1;

int[] array = array2D[0];

Comments

0

Two dimensional array is same as one dimensional array from memory management perspective ( meaning the data is stored in a single dimension). So, first element of two dimensional array is same as the first element of one dimensional array.

4 Comments

I know that multidimensional array is array of arrays in the memory. But int[][] array = new int[5][10] will pass, int[] = new int[3][2] will not. The sizes has to match, but in my example, in my opinion it does not.
I don't think size has to match because each element of 2 dimensional array is just a type of integer. so, i believe int[] array = new int[3][2] will work too.
Bu it doesn't. Try in compiler :p. Message: incompatible types.
You don't have to believe if you can just check it. And btw int[] arrayX = new int[3][2]; will not compile because you are trying to pass two dimensional array of integers to one dimensional one.

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.