aspose file tools*
The moose likes Beginning Java and the fly likes Proving 2-d array stores references Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Proving 2-d array stores references" Watch "Proving 2-d array stores references" New topic
Author

Proving 2-d array stores references

Jeff Bosch
Ranch Hand

Joined: Jul 30, 2003
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


Give a man a fish, he'll eat for one day. Teach a man to fish, he'll drink all your beer.
Cheers, Jeff (SCJP 1.4, SCJD in progress, if you can call that progress...)
Jason Menard
Sheriff

Joined: Nov 09, 2000
Posts: 6450
This recent thread is somewhat relevant.
Jeff Bosch
Ranch Hand

Joined: Jul 30, 2003
Posts: 805
Thanks, Jason.
Regards,
Jeff
 
Don't get me started about those stupid light bulbs.
 
subject: Proving 2-d array stores references