views:

102

answers:

3

I have a 2 dimensional array. Is it necessary to fix the size so that every row has the same number of columns?

data = {{ 2, 6, 3, 3, 1 }, 
        { 4, 6, 3, 7, 5 }, 
        { 8, 3, 0, 0, 0}, 
        { 13, 12, 0, 0, 0 }, 
        { 5, 1, 3, 9, 5, 0}} 
+2  A: 

You can just omit all the ignored values; a java 2d array is just an array of arrays. There's no reason why they have to all be the same length.

Sam Dufel
+5  A: 
{{ 0, 2, 6, 3, 3, 1 },
 { 1, 4, 6, 3, 7, 5 },
 { 0, 8, 3 },
 { 1, 13, 12 },
 { 0, 5, 1, 3, 9, 5 }}

Arrays of arrays in Java do not have to be "rectangular". Just get rid of the sentinel (-1) and the "empty" data after them and use the .length of the sub-array.

TofuBeer
+1  A: 

No, it is not necessary to fix the size for the columns for each row in java's 2D array.

In extension to the answer of "TofuBeer" you can allocate the 2D array dynamically as below. the below sample shows the trangular matrix:

int[][] array2D;

//Allocate each part of the two-dimensional array individually.
array2D = new int[10][];        // Allocate array of rows
for (int r=0; r < array2D.length; r++) {
    array2D[r] = new int[r+1];  // Allocate a row
}

//Print the triangular array (same as above really)
for (int r=0; r<array2D.length; r++) {
    for (int c=0; c<tarray2D[r].length; c++) {
        System.out.print(" " + array2D[r][c]);
    }
    System.out.println("");
}
Dhiraj