Java中的双数组初始化
我正在阅读 Java 上的一本书,并遇到了一个示例,其中数组类型为double初始化的方式是我以前从未见过的.它是什么类型的初始化,还可以在其他地方使用?
I was reading a book on Java and came across an example in which an array of type double was initialized in a way that I haven't seen before. What type of initialization is it and where else can it be used?
double m[][]={
{0*0,1*0,2*0,3*0},
{0*1,1*1,2*1,3*1},
{0*2,1*2,2*2,3*2},
{0*3,1*3,2*3,3*3}
};
这是数组初始值设定项语法,仅在声明数组类型的变量时才能在右侧使用.示例:
This is array initializer syntax, and it can only be used on the right-hand-side when declaring a variable of array type. Example:
int[] x = {1,2,3,4};
String y = {"a","b","c"};
如果您不在变量声明的RHS上,请改用数组构造函数:
If you're not on the RHS of a variable declaration, use an array constructor instead:
int[] x;
x = new int[]{1,2,3,4};
String y;
y = new String[]{"a","b","c"};
这些声明具有完全相同的效果:分配新数组并使用指定的内容构造
These declarations have the exact same effect: a new array is allocated and constructed with the specified contents.
在您的情况下,以编程方式指定表实际上可能更清晰(重复性较低,但不太简洁):
In your case, it might actually be clearer (less repetitive, but a bit less concise) to specify the table programmatically:
double[][] m = new double[4][4];
for(int i=0; i<4; i++) {
for(int j=0; j<4; j++) {
m[i][j] = i*j;
}
}