Java 最好使用一个3d阵列还是两个2d阵列?

Java 最好使用一个3d阵列还是两个2d阵列?,java,performance,multidimensional-array,Java,Performance,Multidimensional Array,如果我想在一个2d数组中存储两个值,那么使用一个3d数组来存储这些值是否具有更好的内存和速度?还是两个二维阵列?例如: int[][][] array = new int[rows][cols][data]; for(int i = 0; i < rows; i++) for(int j = 0; j < cols; j++) { array[i][j][0] = value1; array[i][j][1] = value2;

如果我想在一个2d数组中存储两个值,那么使用一个3d数组来存储这些值是否具有更好的内存和速度?还是两个二维阵列?例如:

int[][][] array = new int[rows][cols][data];

for(int i = 0; i < rows; i++)
    for(int j = 0; j < cols; j++)
    {
        array[i][j][0] = value1;
        array[i][j][1] = value2;
    }

或者这对性能来说真的不重要吗

它们不是我正在使用的大型阵列,最多可能只有100乘100。。但如果要扩大规模,最好使用哪一种

或者,如果性能根本不会受到影响,那么哪种编码方式才是最佳的编码方式


编辑:这与一个java项目特别相关,但更感兴趣的是一般;如果有不同的语言根据所使用的方法而有所不同,那么这些信息对于将来的参考也会很有用。

我认为如果定义一个类来保存值,然后将它们存储在向量或数组列表中,会更容易,也会更好地扩展

比如说

class Values {
    int value1;
    int value2;
}

ArrayList<Values> valueList = new ArrayList<Values>()

for (int i = 0, i <= 100, i++) {
    currentValue = Values();
    currentValue.value1 = i + 1;
    currentValue.value2 = i + 2;
    valueList[i] = currentValue;
}

在性能方面,根据您遍历2d或3d阵列的方式,您可以获得线性或二次顺序的性能。

不知道您真正想要实现的是什么,我想说,您需要的是在矩阵中放置一个具有相关数据的对象,前提是这是对您的问题区域的最佳描述。这意味着

class MeasurePoint {
  int temperature;  // For example
  int windSpeed;

  MeasurePoint(int a, int b) {
    temperature = a;
    windSpeed = b;
  }
}

MeasurePoint[][] map = new MeasurePoint[rows][cols];

for(int i = 0; i < rows; i++) {
    for(int j = 0; j < cols; j++) {
      map[i][j] = new MeasurePoint(value1, value2);
    }
}

Java是面向对象的。利用您可以使用的建模工具。如果您只想遍历内存,那么您也可以使用汇编。

尝试使用映射实现这一点。可以使用row类包含一行的所有数据

public class Row {

    protected int id;
    protected Object other;
    //etc, getters/setters, whatever you need

}

Map<Integer, Row> rows = new HashMap<>();

//...
Row r = this.rows.get(/*row id*/);
if (r == null) {
    //row doesn't exist
} else {
    //work with row object
}

. - KnuthIt最好让类表示您的数据并处理这些数据,而不是对数据中包含的数据进行模糊的引用arrays@Elliot,有趣的链接,但我更感兴趣的是一般做法,因为我目前正在学习。@guskenny83正如您所问的一般做法,使用类以特定的形式表示数据是常见的做法。与对象和高级数据结构相比,数组很少用于数据管理您应该始终选择正确表示数据的表示形式。如果尝试表示三维数据,请使用三维数据结构。如果尝试表示二维数据,请使用二维数据结构。永远不要因为性能原因而选择不那么有代表性的代码,请参阅@Elliot的链接
public class Row {

    protected int id;
    protected Object other;
    //etc, getters/setters, whatever you need

}

Map<Integer, Row> rows = new HashMap<>();

//...
Row r = this.rows.get(/*row id*/);
if (r == null) {
    //row doesn't exist
} else {
    //work with row object
}