Multi-dimensional arrays in Java

二次信任 提交于 2020-01-14 06:53:53

问题


I am preparing for OCAJP exam, I got a problem with the multi-dimensional arrays in java. After go through a video tutorial on YouTube, I think I got an idea about how it works. It says the following statement creates two double dimensional arrays and one array to hold both arrays. Hence it is a three dimensional array.

int arr[][][] = new int[2][4][3];

So I want to get confirmed, that if I want a five dimensional array, this statement would do it.

 int arr[][][] = new int[4][4][3];

回答1:


Try to visualise it geometrically.

  • A 1-dimensional array is just a list: new int[2]

  • A 2-dimensional array is a rectangular grid (or a list of lists): new int[2][3]

  • A 3-dimensional array is a cuboid (or a list of rectangles, or a list of lists of lists): new int[2][3][4]

After this it gets harder, but :

  • a 4D array is a list of cuboids (a list of lists of lists of lists) new int[2][3][4][5]

  • a 5D array is a grid of cuboids (a list of lists of lists of lists of lists): new int[2][3][4][5][6]




回答2:


int arr[][][] = new int[4][4][3];

Is still a 3 dimensional array.

A 5 dimensional array looks like

 int arr[][][][][] = new int[4][4][3][4][3];



回答3:


int arr[][][][][] = new int[4][4][3][X][X];

x can be any number. this is a 5 dimentional array.




回答4:


Imagine a cube.

int arr[][][] = new int[2][4][3];

Here you have 2 slices of an array of 4x3.

int arr[][][] = new int[4][4][3];

With this, you have 4 slices of an array of 4x3.

So, it stills a three dimensional array. However, you can save 4 different two dimensional arrays there.




回答5:


every time you add a new dimension the number of elements grow exponentially. int[4][4][3] means a 3-dimensions array with 4*4*3=48 elements. to create a 5-dimension array add 2 more square-brackets int[2][2][2][2][2] which is an array with 2^5 elements(2*2*2*2*2)



来源:https://stackoverflow.com/questions/24597504/multi-dimensional-arrays-in-java

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