In Java, when is the {a,b,c,…} array shorthand inappropriate, and why?

江枫思渺然 提交于 2019-12-01 15:18:07

问题


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}
    }

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?

Edit: 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?


回答1:


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.

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




回答2:


You can use braces notation only at the point of declaration, where compiler can infer the type of array from the declaration type.

To use it anywhere else you need to use Array Creation Expression:

return new double[] {0,1,2};



回答3:


One more edge case I found was in the creation of a two dimensional array and initializing the arrays in the two dimensional array

So from Jeffrey's response - https://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html#jls-10.6 - "An array initializer may be specified in a declaration, or as part of an array creation expression", the below code should appear to work because the the array initializer is being used to initialize the array

int[][] grid = new int[3][3];
grid[0] =  {1,1,1};

However this didn't work(compilation error), and I had to rewrite this as

grid[0] =  new int[]{1,1,1};


来源:https://stackoverflow.com/questions/17933864/in-java-when-is-the-a-b-c-array-shorthand-inappropriate-and-why

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!