我如何初始化在Java这个二维数组? [英] How do i initialize this 2D array in java?
问题描述
我要寻找宣称可以在低于code仅持有3个不同的值二维数组的类型。
这可能是什么二维数组,可以采取至少存储每个单元格并保持3个不同值之一的类型?然后我会使用循环初始化数组等。
类网{
X [] [] twoDimArray =新的X [3] [3]; 格(){ } 无效printElements(){
}
}
有关三个值,一个枚举
十分引人注目;
枚举ExampleEnum {
一二三; @覆盖
公共字符串的toString(){
开关(本){
情况一:
回到一;
案例二:
回到二;
默认:
返回三公;
}
}
}
那么你的数组声明可能的样子,
ExampleEnum [] [] = twoDimArray新ExampleEnum [3] [3];
和你可以使用<一个href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#deepToString%28java.lang.Object[]%29\"相对=nofollow> Arrays.deepToString(对象[])
像输出
的System.out.println(Arrays.deepToString(twoDimArray));
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(){
}
}
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));
这篇关于我如何初始化在Java这个二维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!