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

后端 未结 3 1054
暖寄归人
暖寄归人 2021-01-17 09:53

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}};
相关标签:
3条回答
  • 2021-01-17 10:37

    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};
    
    0 讨论(0)
  • 2021-01-17 10:43

    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.

    0 讨论(0)
  • 2021-01-17 10:46

    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};
    
    0 讨论(0)
提交回复
热议问题