我现在不知道如何正确地描述它,但我会尝试/
我有一个 Java 中的二维整数数组。现在我想在一个位置上写点东西。
通常我需要这样做 array[a][b]=x;
.
我还有一个带有两个值 {a,b}
的数组 z
有没有办法可以简化 x
值的编写在那里?
目前我正在这样做:array[z[0]][z[1]] = x
但是有更简单的方法吗?
最佳答案
编写一个类来包含数组并使用 getter 和 setter 访问其元素。
public static class Array2D {
private int[][] array;
public Array2D(int x, int y) {
array = new int[x][y];
}
public int get(int[] index) {
return array[index[0]][index[1]];
}
public void set(int[] index, int val) {
array[index[0]][index[1]] = val;
}
}
public static void main(String[] args) {
Array2D array = new Array2D(2, 8);
int[] coords = { 1, 5 };
array.set(coords, 5);
System.out.println(array.get(coords));
}
关于java - 与其他数组打开数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47608266/