• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

array assignments

 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Correction in the above question, I meant any element b2[x][y], instead of b[x][y].
Thank you
 
Ranch Hand
Posts: 539
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic