Java: Jagged Array
Jagged Array
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. e.g.
int[] xx
- Initialize and declare size. e.g.
xx = new int[10];
- Assign values to slots. e.g.
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 }};
.
Array Cannot be Arbitrary Tree
Middle level nodes cannot have different count of elements.
For example, you cannot create a array with a shape like this: { { 3, 4, 5 }, { 77, 50, {1, 2} }}