Java中的双数组初始化 [英] Double array initialization in Java

查看:89
本文介绍了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;
    }
}

这篇关于Java中的双数组初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆