programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Array Confusion

Mike London
Ranch Hand
Posts: 1505
11
In the code below, two arrays are created, but the blueInvert array creates a two dimensional array of shorts, but initializes it with three arguements.
What is going on? When creating the new short[][] array, shouldn't there only be two arguements instead of three (new short[][] { straight, straight, invert)???
Code==========================================
short[] invert = new short[256];
short[] straight = new short[256];
for (int i = 0; i < 256; i++)
{
invert[i] = (short)(255 - i);
straight[i] = (short)i;
}
// what's going on here?
// this looks like a two dimensional arrray, short
// is being created, but it's given three
// arguements?
short[][] blueInvert = new short[][] { straight, straight, invert };
==============================================

Cindy Glass
"The Hood"
Sheriff
Posts: 8521
blueInvert has been initialized with 3 ELEMENTS each of which is an array itself.
That makes blueInvert an array of arrays.
Be careful using that "multi-dimensional" word. There is a difference between an array of arrays:
myArray[3][B]
and a multi-dimensional array (which java does NOT have) which would be expressed by:
myArray[3xB]
Some languages allow both concepts.

Layne Lund
Ranch Hand
Posts: 3061
Cindy is correct that there is a difference between a multi-dimensional array and an array of arrays. However, conceptually, I usually think of them as the same thing.
I think the error in your thinking is that the arrays used to initialize the so-called 2D array has nothing to do with the dimensions. Just think of each of the elements that initialize blueInvert as the rows of the array. So here blueInvert is a 2D array with 3 rows and 256 columns.
I see a potential problem with this code. If you change an element in the first row of blueInvert, say
blueInvert[0][1] = 10;
It changes the corresponding element in straight, which in turn means that it changes the same element in the second row of blueInvert. This has to do with object references.
Someone correct me if I am wrong here, but I don't think blueInvert makes copies of the arrays that it's initialized with.

Mike London
Ranch Hand
Posts: 1505
11
Thanks Layne!
Yes, you're right I wasn't thinking correctly about the three elements (confusing them with "dimensions") still intializing a two-D arrray.
This code came from an online posting of some graphics routines in JavaWorld magazine from a while back. I was reading it and got a bit confused by this array initialization.
It's clear now.
Thanks again!!!
-- Mike