[英]How do i initialize this 2D array in java?
I am looking for declaring the type of 2D array that can hold only 3 distinct values in the below code. 我正在寻找声明下面的代码中只能容纳3个不同值的2D数组的类型。
What could be the type of the 2D array that can take least memory for each cell and hold one of the 3 distinct values? 可以占用每个单元最少内存并保存3个不同值之一的2D数组的类型是什么? I would then initialise such array using for-loop.
然后,我将使用for循环初始化此类数组。
class Grid{
X[][] twoDimArray = new X[3][3];
Grid(){
}
void printElements(){
}
}
如果需要三个不同的值,则byte [] []可能是最有效的,可以明智地使用内存。
For three values, an enum
is very compelling; 对于三个值,一个
enum
非常引人注目。
enum ExampleEnum {
ONE, TWO, THREE;
@Override
public String toString() {
switch (this) {
case ONE:
return "One";
case TWO:
return "Two";
default:
return "Three";
}
}
}
Then your array declaration might look like, 然后,您的数组声明可能看起来像,
ExampleEnum[][] twoDimArray = new ExampleEnum[3][3];
And you could use Arrays.deepToString(Object[])
for output like 而且您可以使用
Arrays.deepToString(Object[])
进行输出,例如
System.out.println(Arrays.deepToString(twoDimArray));
If, just if, you would need to reduce resource usage, one could store the entire grid in an int, two bits per diagram position, 9 positions: 18 bits. 如果只是,如果您需要减少资源使用,则可以将整个网格存储在一个int中,每个图位置两位,9位:18位。
int diagram;
int getValue(int x, int y) {
int i = 2*(x + 3*y);
return (diagram >>> i) & 0x3;
}
void setValue(int x, int y, int value) {
int i = 2*(x + 3*y);
int mask = 0x3 << i;
diagram &= ~mask;
diagram |= value << i;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.