【问题标题】:Understanding Three-Dimensional Arrays了解三维数组
【发布时间】:2012-07-22 08:45:57
【问题描述】:

我正试图将我的头脑围绕在 3D 数组上。我知道它们是二维数组的数组,但是我正在阅读的书说了一些让我感到困惑的事情。

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

如果我们决定选择一个 3 维数组,数组的声明方式如下:

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

但是,这样不是更有效吗?

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

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

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

【问题讨论】:

  • 是一样的。你可以随意使用尺寸,只要它是一致的。没有性能或内存差异。
  • 您为什么认为订单会有所作为?
  • @Luxspes 我不相信。我知道。
  • @Bohemian 抱歉,我在和 Jake Wilson 说话,而不是在和你说话
  • @Bohemian 还有.. 你是什么意思?根据我的阅读,您和我一样,相信顺序没有区别......所以......你想说什么?

标签: java multidimensional-array


【解决方案1】:

顺序无关紧要,所以一个并不比另一个更有效。唯一重要的是任何访问 colorImage 的东西都知道哪个维度用于什么。多维数组here的更多上下文。

【讨论】:

    【解决方案2】:

    顺序无关紧要,实际上前一种形式更具可读性:

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

    【讨论】:

      【解决方案3】:

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

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

      您需要一个 int,因为您要处理超过 256 个列和行。 (没关系)。 但我认为将颜色信息封装在一个额外的对象中要好得多。也许像

      这样的私有数据结构
      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 类公开给您的整个应用程序 - 我会更改该类的设计以更安全。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-27
        相关资源
        最近更新 更多