理解三维数组

我试图围绕三维数组。 我知道它们是二维数组的数组,但是我正在读的那本书让我感到困惑。

在我正在阅读的这本书的练习中,它要求我为全彩色图像制作一个三维数组。 它给出了一个小例子说:

如果我们决定选择一个三维数组,这里是如何声明数组:

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

但是,这不是更有效吗?

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

其中3是rgb值,0表示红色,1表示绿色,2表示蓝色。 对于后者,每个二维数组都会存储行和列的颜色值,对吧? 我只是想确保我理解如何有效地使用三维数组。

任何帮助将不胜感激,谢谢。

顺序无关紧要,事实上前一种forms更具可读性:

 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]; 

订单无关紧要,因此一个不比另一个更有效。 唯一重要的是无论访问colorImage知道哪个维度用于什么。 这里在多维数组上有更多的上下文。

我不确定将所有内容都放在int的3dimensional数组中是否是个好主意。

你的第一个错误是dataytpe:RGB是一个int。 但是R是一个字节,G是一个字节,B也是一个字节..( Color.getXXX()提供一个int,我不知道为什么因为它的字节0-255)

你需要一个int,因为你想要处理超过256个cols和行。 (没关系)。 但我认为将颜色信息封装在额外的对象中要好得多。 也许像私人数据结构一样

 class MyColor { public byte r, g, b; //public for efficient access; public int color; //public for efficient access; public MyColor(final int rgb) { this(new Color(rgb)); } public MyColor(final Color c) { this((byte) c.getRed(), (byte) c.getGreen(), (byte) c.getBlue(), c.getRGB()); } public MyColor(final byte red, final byte green, final byte blue, final int c) { this.r = red; this.g = green; this.b = blue; this.color = c; } } 

并把它放在MyColor[numRows][numColumns]的2dim数组中

但是如果你将MyColor类公开到你的整个应用程序 – 我会改变类的设计以使其更安全。