Ly Maneug - 11 months ago 65

Java Question

In java, say for example I have

`char[][] board`

`board.length`

`board[0].length`

`board.length`

`board[0].length`

Thank you

Answer Source

A 2-dimensional array has no intrinsic notion of "x" and "y", or "width" and "height". A 2-dimensional array doesn't even really have the notion of being 2-dimensional: it is a 1-dimensional array of "things", where each of those things is a 1-dimensional array.

So a `char[][]`

is a 1-dimensional array where every element is a `char[]`

; and every `char[]`

is a 1-dimensional array where every element is a `char`

. Notice that there's not even a requirement for the contained arrays to be of the same length as each other.

As such, you can't ask "Is board.length the length of the x axis and y axis for the board[0].length?": they represent that if that's how you choose to construct and interpret your array.

Consider constructing an array like this:

```
char[][] board = new char[3][4];
```

This makes a 2-dimensional array, where all of the 3 sub-arrays have length 4.

Applying your description, it can be visually represented like this:

So here, the `i`

in `[i][j]`

represents the x-coordinate, and the `j`

represents the y-coordinate. Hence, `board.length`

would be the x size, and `board[0].length`

would be the y size.

But here's another way of interpreting the same 2-dimensional array, where the x- and y-axes are transposed.

Now, the `i`

in `[i][j]`

represents the y-coordinate, and the `j`

represents the x-coordinate. Hence, `board.length`

would be the y size, and `board[0].length`

would be the x size.

Neither is right, neither is wrong. It depends upon what you're trying to represent as to which you choose.