在 Java 中,什么时候 {a,b,c,...} 数组简写不合适,为什么? [英] In Java, when is the {a,b,c,...} array shorthand inappropriate, and why?

查看:26
本文介绍了在 Java 中,什么时候 {a,b,c,...} 数组简写不合适,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您正在定义一个变量,那么声明/定义一个变量似乎是完全有效的:

If you're defining a variable, it appears to be perfectly valid to declare/define a variable as follows:

    double[][] output = {{0,0},{1,0}};

但是如果您要返回一个值,则编写以下内容似乎是无效的:

But if you're returning a value, it appears to be invalid to write the following:

    public double[] foo(){
      return {0,1,2}
    }

我本以为在内部,这两者都会执行相同的操作.至少 Eclipse 不同意.有谁知道有什么区别,还有什么地方可以看到,或者为什么接受前一个例子而拒绝后者会有好处?

I would have thought that internally, both of these would have been performing the same action. Eclipse, at least, disagrees. Does anyone know what the difference is, and where else it can be seen, or why it would be beneficial to accept the former example and reject the latter?

好的,所以当你初始化时它是合适的,但我没有看到任何歧义......JVM不能从变量的名称解释变量的类型(在已经重新定义的情况下)初始化变量)或返回时(JVM 可以只查看函数的返回类型)?什么使初始化成为禁止隐式类型的规则的特例?是什么让一般规则要求显式类型?

okay, so it's appropriate when you're initializing, but I don't see any ambiguity... couldn't the JVM interpret the type of variable from the name of the variable (in the case of redefining already initialized variables) or when returning (where the JVM could just look at the return type of the function)? What makes initialization a special case of a rule that would prohibit implicit type? What makes the general rule require explicit type?

推荐答案

仅在声明时才可接受.但是,您可以使用 new double[] {0, 1, 2}.

It's only acceptable during a declaration. You can, however, use new double[] {0, 1, 2}.

JLS §10.6:

数组初始值设定项可以在声明中指定,也可以作为声明的一部分一个数组创建表达式.

An array initializer may be specified in a declaration, or as part of an array creation expression.

数组创建表达式是new double[] { } 语法.

An array creation expression is the new double[] { } syntax.

这篇关于在 Java 中,什么时候 {a,b,c,...} 数组简写不合适,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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