-3

I am looking for the dimensions of a 2d array. Not the fixed values assigned to the array, but the values containing integers. Example:

int a[][] = new int[4][5];
a[1][1] = 1;
a[1][2] = 2;
a[1][3] = -2;
a[1][4] = 0;
a[2][1] = -3;
a[2][2] = 4;
a[2][3] = 7;
a[2][4] = 2;
a[3][1] = 6;
a[3][2] = 0;
a[3][3] = 3;
a[3][4] = 1;

Only 3 variables are used out of 4, and 4 variables used out of 5. How can you tell what is actually there versus what is assigned to be there?

array.length;
array[0].length;

The previous code will only give you the fixed variable assigned to the array. But what if your not using all the variables? In other words I am looking for an output of 3 for columns and 4 for rows.

Tyler
  • 7
  • 4
  • You can't. Array is filled with default values like `0` `false` `null` (depending on type). Since you are using `0` as proper value you can't know if rest of zeroes are default (unused) or actually set up by someone else. – Pshemo Dec 06 '17 at 18:35

3 Answers3

0

In your code example, you are using all variables in the array. Just because you haven't assigned anything to them, they are still sitting there.

If you want to determine whether or not you've assigned a value to each element in the array, you need to initialize everything to a default value, and then just compare against the default value.

A variation on that option is to declare them as int?, which is a nullable int. That would allow you to set everything to null, and then you'll know that the elements that are no longer null have had a value assigned to them.

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466
0
    // using Integer instead of int, which is a nullable object
    Integer a[][] =  new Integer[4][5];
    int cnt1 = 0;
    for(int i = 0; i < a.length; i++) {
        for(int j = 0; j < a[i].length; j++) {
            if(a[i][j] != null) {
                cnt1++;
            }
        }
    }
    System.out.println(cnt1 + " array indices are non-null.");

    // using int
    int b[][] =  new int[4][5];
    for(int i = 0; i < b.length; i++) {
        for(int j = 0; j < b[i].length; j++) {
            b[i][j] = -9999;
        }
    }

    int cnt2 = 0;
    for(int i = 0; i < b.length; i++) {
        for(int j = 0; j < b[i].length; j++) {
            // pick a value that will never be assigned
            if(b[i][j] != -9999) {
                cnt2++;
            }
        }
    }
    System.out.println(cnt2 + " array indices are not -9999.");
Joseph Ryle
  • 129
  • 5
0

You can't do it dynamically. Once you've initiated your matrix like that (new int[4][5]) you have and matrix of 0.

You must initiate the matrix ant set an invalid value to all posistions, something like -1 or whatever you wan't and iterate over it to discover the result

Rômulo M. Farias
  • 1,483
  • 1
  • 15
  • 29