user225626
user225626

Reputation: 1099

Initializing (and calling) some sort of 2D array for this:

As I LogCat the following I thought it would be nice to affiliate the size outputs with corresponding field labels to the left of a colon, e.g., "This is the red component: [EGL10.EGL_RED_SIZE]," etc.

int[] attrib = { 
    EGL10.EGL_RED_SIZE, 
    EGL10.EGL_GREEN_SIZE, 
    EGL10.EGL_BLUE_SIZE, 
}; 

for(int n = 0; n < 3; n++){
    egl.eglGetConfigAttrib(eglDisplay, config[0], attrib[n], some_value);
    Log.v(TAG, String.format("SIZE = %d", some_value[0]));
}

Obviously at present I only output:

5
6
5

..., etc.

Alternatively, I could create an 'attribDefs' array loaded with my hardcoded field descriptors separate from the attrib array, and just concatenate the results on the LogCat--maybe that might even be a preferable solution.

I was just wondering what the same thing might look like as a 2D array; how would such a 2D construct look in the attrib array intitialization? (This isn't a trick question or anything; I'm a Java noob.) Thanks.

Upvotes: 1

Views: 285

Answers (1)

polygenelubricants
polygenelubricants

Reputation: 383686

I have no idea what you're doing, but perhaps this snippet helps:

    int[][] table = {
            { 1, },
            { 2, 3, },
            { 4, 5, 6 },
            { },
            { 7, },
    };
    for (int[] row : table) {
        int sum = 0;
        for (int num : row) {
            sum += num;
        }
        System.out.println("Row sum is " + sum);
    }

This prints:

Row sum is 1
Row sum is 5
Row sum is 15
Row sum is 0
Row sum is 7

It uses the "foreach" loop for readability, since explicit index is not required for this particular case. Note also that Java doesn't have "multidimensional arrays", but rather array of arrays, which allows for the jaggedness characteristics in this example.

For explicit indexing, you can do, among other things, something like this:

    for (int i = 0; i < table.length; i++) {
        for (int j = 0; j < table[i].length; j++) {
            System.out.print(table[i][j] + " ");
        }
        System.out.println();
    }

This prints:

1 
2 3 
4 5 6 

7 

Whenever you have a choice, you should prefer the "foreach" loop to explicit indexing, as it's more readable and less error prone.

References

See also

  • Effective Java 2nd Edition, Item 46: Prefer for-each loop to traditional for loops

Upvotes: 2

Related Questions