I am looking for declaring the type of 2D array that can hold only 3 distinct values in the below code.
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? I would then initialise such array using for-loop.
class Grid{
X[][] twoDimArray = new X[3][3];
Grid(){
}
void printElements(){
}
}
如果需要三个不同的值,则byte [] []可能是最有效的,可以明智地使用内存。
For three values, an enum
is very compelling;
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
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 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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.