Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maximum number of dimensions in a Java array

Tags:

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

like image 544
Adam Avatar asked Oct 30 '10 20:10

Adam


People also ask

What is the maximum number of dimensions in array?

Theoratically no limit. The only practical limits are memory size and compilers.

Can Java have 4 dimensional arrays?

You could create a Sodoku hypercube with 4 dimensions and stores the numbers the user enters into a 4dimensional int array.

Can Java have 3 dimensional arrays?

Array elements are accessed by the numeric indexes, with the first element stored at 0 indexes. There are basically two types of arrays in Java, i.e. one-dimensional and multi-dimensional arrays. 3D arrays fall under the category of multidimensional arrays.

Can an array have more than 3 dimensions?

Multidimensional arrays don't need to be conceptualised as rectangles, cubes, etc. There is another way of looking at them. A 2-dimensional array is a 1-dimensional array of equal-sized 1-dimensional arrays. A 3-dimensional array is a 1-dimensional array of 2-dimensional arrays.


1 Answers

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.")

like image 71
kennytm Avatar answered Oct 02 '22 07:10

kennytm