Search code examples
javaarraysshort

2-D and 1-D arrays


First of all, here's the code:

public class Test{

   public static void main(String args[]){

    short[][] b = new short[4][4];
    short[][] big = new short[2][2];
    short b3 = 8;
    short b2 [][][][] = new short [2][3][2][2];

   // insert code here that will allow the code to compile

     }

}

This is a problem from a textbook, here are the two answers that are wrong:

b2[0][1][1] = b;

The explanation here is that it tries to assign a 2-dimensional array where a 1-dimensional array is expected. Can someone explain this? I do not see where a 1-dimension array is in the code at all.

b2[0][2][1] = b[1][0];

The explanation for this wrong answer is that it tries to assign a primitive short where a short array is expected. I'm baffled by this one because I don't see a primitive short in this answer?


Solution

  • in java a multi-dimentional array is actually an array of arrays.

    You can think of it as though every time you index the array(that means you put [i] after it) you lose a dimention.

    b
    

    gives a 2-dimentional array,

    b[i] 
    

    gives you a 1-dimentional array, and

    b[i][j]
    

    gives you a short (which is a primitive)

     b2[0][1][1]
    

    should also give you a 1 dimentional array, but you're trying to put a 2-dimentional array there, which is the problem.

    now for the second wrong answer, b[i][j] gives you a primitive., and that's what you're trying to put where the 1-dimentional array should be.