This week's book giveaway is in the Design forum.We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!

# Proving 2-d array stores references

Jeff Bosch
Ranch Hand
Posts: 805
I've seen (and experienced in my youth, which was only a few weeks ago I think) some confusion about the true nature of two-dimensional arrays in Java. I hope this explanation by example helps clear some of the fog for newbies.
A two dimensional array consists of a one dimensional array of references to one-dimensional arrays. The following code uses standard Java reference equality tests and reference reassignment to prove this.
First, we create a two-dimensional array of primitive int values. The program then prints the length, and calls a method for printing the array contents. If the two-dimensional array, intArray, were on object containing all elements listed in the initialization, the program would print "intArray has 12 elements". But, it prints "intArray has 3 elements", which corresponds to the number of inner braces in the initialization.
Calling printArray(), we see each array, its length, and its contents. If intArray were one object, it's elements intArray[0], intArray[1] and intArray[2] would not have individual length attributes.
Next, we create a one-dimensional int array, int2, and assign it to intArray[2]. Calling printArray() now shows that intArray[2] has been replaced by the new int2 array. Only another reference to an array object, like intArray[2], would have been validly assigned to the array referenced by int2.
For our final proof, we have the reference equality test, which proves that intArray[2] and int2 point to the same object because their references are equal.

I hope this helps clarify how multidimensional arrays work. If I put anybody to sleep with this, though, then maybe I'll just bottle it as a cure for insomnia!
Regards,
Jeff

Jason Menard
Sheriff
Posts: 6450
This recent thread is somewhat relevant.

Jeff Bosch
Ranch Hand
Posts: 805
Thanks, Jason.
Regards,
Jeff