Wednesday, May 18, 2011

Types of 2D arrays in java

2D arrays in java are of 2 types – even and ragged or uneven arrays.

Defining an even array

Here, Each row of a 2D array may have a same number of cells in the array.

int twoD[][] = new int[4][];
twoD[0] = new int[5];
twoD[1] = new int[5];
twoD[2] = new int[5];
twoD[3] = new int[5];


Defining non-uniform or ragged arrays


Here, each row of a 2D array may have a different number of cells.


int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];


Similarly we can initialized ragged arrays like :


int[][] uneven = 
{ { 1, 9, 4 },
{ 0, 2},
{ 0, 1, 2, 3, 4 } };

No comments:

Post a Comment

Chitika