Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I reference multi-dimensional arrays?
    primarykey
    data
    text
    <p>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:</p> <pre><code> //************************************ // 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 </code></pre> <p>Why is it 21? I thought it would be 22.</p> <p>I looked this up because I am trying to figure out what length means in this context:</p> <pre><code>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); } } </code></pre> <p>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? </p> <p>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)?</p> <p>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.</p> <p>Thank you for your helping me understand.</p> <p>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?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload