Originally posted by Spencer Lee:
I just thought i'd post my afterthoughts since my original posting...
I'm guessing that 2D array access like my_array[][2] is not allowed because of the way the memory is laid out...
Could it be that array access like my_array[0] (for a 2D array variable that is declared as my_array[][] = new String[4][3] for example) is permitted because the memory of the first dimension is laid out contiguosly, but my_array[][2] is not because the memory not laid out contiguously?
Any thoughts?
Multi-dimensional arrays in Java are handled a little bit differently than multidimensional arrays in some other languages you may be familiar with. Java multi-dimensional arrays are actually arrays of arrays (of arrays of arrays...).
So while you may be used to thinking of a 2D array as a matrix, this isn't necessarily the case in Java. For example, initializing a 2d array in the following manner is perfectly legal:
String[][] sa = new String[5][]; Looking at the above, sa[0], sa[1], sa[2], etc... are each references to a String[]. In this case these references are actually null. If we do this:
sa[0] = new String[3]; sa[0] now contains a reference to a String[] of size 3, and sa[1] through sa[4] still point to null. The consequence of handling arrays in this manner is that, like I mentioned earlier, multi-dimensional arrays do not have to be matrix-like, but rather they can be "jagged" so to speak. Keeping in mind that we set sa[0] to be a reference to a String[] of size 3, the following is also perfectly legal:
sa[1] = new String[15]; This is what I meant by "jagged". sa[0] points to an array of size three while sa[1] points to an array of size 15! I could then go and fill in String values for sa[0][0], sa[0][1], sa[0][2], as well as values for sa[1][0] through sa[1][14].
You should realize by now that
sa[0][1] = "foo"; is the same as
String[] myArray = sa[0];
myArray[1] = "foo"; This should go some way to helping explain why you cannot make a reference such as
sa[][2]. While a language like C maps out a contiguous block of memory and you could use pointer arithmetic to navigate between the memory addresses, the same wouldn't work in Java (even if you could theoretically access memory directly using pointers). More practically, you can't be assured that just because
sa[0][2] is a valid reference, that
sa[1][2] is also a valid reference, particularly since sa[1] might be less than size 3, in which case an
ArrayIndexOutOfBoundsException would be thrown.
HTH
[ August 24, 2003: Message edited by: Jason Menard ]