I'm trying to understand multi-dimensional arrays in Java, but I think it applies to any language. Please consider this snippet I found on the web:
//************************************
// static array initialization
//************************************
byte[][] smallArray = { { 10, 11, 12, 13 },
{ 20, 21, 22, 23 },
{ 30, 31, 32, 33 },
{ 40, 41, 42, 43 }, };
// Display the array element at row 2, column 3
System.out.println(smallArray[1][2]);
// Value is 21
Why is it 21? I thought it would be 22.
I looked this up because I am trying to figure out what length means in this context:
public class Pieces {
int thePieces[][][];
public Pieces(){
}
public int[][][] createPieces(){
/* pieces in order below
**** [0]
**
**
*
****
*
****
***
*
**
**
**
** [6]
*
*
*
*/
int myPieces [][][] =
{
{ //square
{0,0},
{1,0},
{1,1},
{0,1}
},
{ //T
{-1,0},
{0,0},
{0,1},
{1,0}
}
};
thePieces = myPieces;
return thePieces;
}
public void printPieces(){
System.out.println(thePieces[0][0].length);
}
}
I am trying to learn java by creating a tetris clone. What I don't understand is why length is required to use [][]. It was the only way I could get to work. I tried thePieces[0][0][0].length but got an error that I did not understand?
Why don't I have to put [][][] to get the reference? I saw online where the first "level" of the array was referenced myArray.length instead of myArray[].length. What then am I saying with myArray[][].length (it seems 2nd,3rd levels but I'm not getting what I expect)?
I ran my piece code and got 2. I have no idea why it is two. Is it because I have two sets at the third level? I expected to get four because of the four sets of points.
Thank you for your helping me understand.
EDIT: I figured out why it is two. It is giving me my two points in the innermost set. If I wanted four I would use thePieces[0].length. But what about the first example? Is it a typo?