Maximum number of dimensions in a Java array

前端 未结 3 1898
借酒劲吻你
借酒劲吻你 2020-12-01 16:00

Out of curiosity, how many dimensions of an array can you have in Java?

相关标签:
3条回答
  • 2020-12-01 16:33

    Small experiment shows, that 255 dimensions is maximum. 256 causes compilation error;

    The screenshot

    0 讨论(0)
  • 2020-12-01 16:40

    The Java language does not limit the number of dimensions, but the Java VM spec limits the number of dimensions to 255.

    For example, the following code will fail to compile:

    class Main {
        public static void main(String[] args) {
            final int[][][][][][][][][][][][][][][][]
                     [][][][][][][][][][][][][][][][]
                     [][][][][][][][][][][][][][][][]
                     [][][][][][][][][][][][][][][][]
                     [][][][][][][][][][][][][][][][]
                     [][][][][][][][][][][][][][][][]
                     [][][][][][][][][][][][][][][][]
                     [][][][][][][][][][][][][][][][]
                     [][][][][][][][][][][][][][][][]
                     [][][][][][][][][][][][][][][][]
                     [][][][][][][][][][][][][][][][]
                     [][][][][][][][][][][][][][][][]
                     [][][][][][][][][][][][][][][][]
                     [][][][][][][][][][][][][][][][]
                     [][][][][][][][][][][][][][][][]
                     [][][][][][][][][][][][][][][][] x;
        }
    }
    

    with error:

    1.java:18: error: array type has too many dimensions
                     [][][][][][][][][][][][][][][][] x;
                                                      ^
    1 error
    

    (Ref: https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.4.1 "An array type descriptor is valid only if it represents 255 or fewer dimensions.")

    0 讨论(0)
  • 2020-12-01 16:45

    Strictly speaking about

     Maximum number of dimensions in a Java array
    

    is only one dimensional array is possible in java. because under the hood java treat multidimensional arrays as array of arrays.

    Proof of concept: http://www.willamette.edu/~gorr/classes/cs231/lectures/chapter9/arrays2d.htm

    that's why its possible to have ragged arrays in Java as well!

    0 讨论(0)
提交回复
热议问题