Understanding Three-Dimensional Arrays

java, multidimensional-array

Solution

Order doesn't matter, and in fact the former form is more readable:

final const int RED = 0;
final const int GREEN = 1;
final const int BLUE = 2;

int[][][] colorImage = new int[numRows][numColumns][3];
//...

int x = getSomeX();
int y = getSomeY();

int redComponent = colorImage[x][y][RED];
int greenComponent = colorImage[x][y][GREEN];
int blueComponent = colorImage[x][y][BLUE];

Problem

I'm trying to wrap my head around three-dimensional arrays. I understand that they are arrays of two-dimensional arrays, but the book I'm reading said something that confuses me. In an exercise for the book I'm reading, it asks me to make a three-dimensional array for a full-color image. It gives a small example saying this: If we decide to choose a three-dimensional array, here's how the array might be declared: ``` int[][][] colorImage = new int[numRows][numColumns][3]; ``` However, wouldn't it be more effective like this? ``` int[][][] colorImage = new int[3][numRows][numColumns]; ``` Where 3 is the rgb values, 0 being red, 1 being green, and 2 being blue. With the latter, each two-dimensional array would be storing the color value of the row and column, right? I just want to make sure I understand how to effectively use a three-dimensional array. Any help will be greatly appreciated, thanks.

Original source