Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

array assignments

 
harsha soma
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello all,
The following code is compiling successfully.

public class arraryTest
{
public static void main(String[] args)
{
short[][] b = new short[4][4];
short[][][][] b2 = new short[2][3][2][2];
b2[1][1] = b;
}
}

My assumption is, any element b[x][y], where x is in (0,1) and y is in (0,1,2), should be a two dimensional array of size 2x2.

But short array b is a two dimensional array of size 4x4.

Shouldn't the compilation fail?
This is very counter-intuitive to me. When I run this program this does not throw any run-time exception either.
I greatly appreciate any correct reasons for this.
 
harsha soma
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Correction in the above question, I meant any element b2[x][y], instead of b[x][y].
Thank you
 
Tim West
Ranch Hand
Posts: 539
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Multidimensional arrays are constructed as "arrays of arrays". So, when you have int[][] myArr = new int[2][2];, "myArr", is a one dimensional array, but each element is itself an array. So, it seems like myArr is two dimensional.

Because myArr is just an array, it behaves the same as any array - each element must be of the correct type. This means you can assign any int[] to an element of myArr. Eg, you could do "myArr[1] = new int[50];". Assignment between array types, as you point out, doesn't do any length checking.

The initialisation code "new int[2][2]" creates an initial 'matrix' of size 2x2, but there is no restriction that myArr must always reference a 'matrix' of this size.

Cheers,


-Tim
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic