1

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
  • Please don't delete a valid question with a valid answer. If you're done with this question, accept the correct answer, and ask a new question if you need to. Commented Oct 17, 2010 at 2:57
  • Okay i will rephrase the question to fix the answer and accept Commented Oct 17, 2010 at 3:12

3 Answers 3

5
{{ 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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

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("");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.