Java: Jagged Arrays
You can create a 2D array with m rows and each row have different number of slots.
public class Aj { public static void main(String[] args) { int[][] xx = { { 3, 4, 5 }, { 77, 50 }}; for (int i = 0; i < xx.length; i++) { for (int j = 0; j < xx[i].length; j++) { System.out.print(xx[i][j] + " "); } System.out.println(); } } } // prints // 3 4 5 // 77 50
Normally, array creation takes 3 steps in java:
- Declare the datatype. For example,
int[] xx
- Initialize and declare size. For example,
xx = new int[10];
- Assign values to slots. For example,
xx[0]=3; xx[1]=5;
There's a irregular syntax that does all the above steps in one, like this: int[][] xx = { { 3, 4, 5 }, { 77, 50 }};
.
Note: even though the leafs of a array can be jagged, but not any middle level nodes. So, arbitrary tree cannot be created as array. For example, you cannot create a array with a shape like this: { { 3, 4, 5 }, { 77, 50, {1, 2} }}