0

In Java, I'd like to get the maximum element from both dimensions of a simple image array, ie:

int getWidth(Color[][] pixels){
    //return max of dimension 1
}

int getHeight(Color[][] pixels){
    //return max of dimension 2
}

I know how to do this for a 1D array in Java, I would just run a for loop with the condition of i < pixels.length. However, I'm not quite sure how .length works for a 2D array, or even if it does work. How would I approach this?

2 Answers 2

1

Will .length still work?

A 2D array is just simply an array, where the items in it are other arrays. Since .length works on a 1D array, it will surely work on all arrays - the amount of dimensions does not matter.

However, pixels.length gives you the length of the parent array - i.e. the array that contains all of the other arrays inside it. To get the length of the second dimension, you will have to get the length of the arrays inside it.

So, how do we get the length of the 2nd dimension?

We know that all of these arrays must be the same length, so we use the one at position 0 only because it is the only one that we can be 100% sure will always exist - an array should always have at least one element.

Then, we just get the length of that array - pixels[0].length.

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

2 Comments

Ah, perfect, that's exactly what I needed to know. Thank you, will accept when possible.
Awesome, glad I could help :D
0

If we consider 2D array they it is an array holding references to other arrays. If we consider matrix like this:

{
    {1,2,3},
    {4,6},
    {7,7,8,9}
}

So height for above matrix is 3 = no. of rows.

Width of matrix is 4 = Max(no. of element in each array).

int getHeight(Color[][] pixels) {
    return pixels.length;
}

int getWidth(Color[][] pixels) {
    int maxCount = 0;
    int rows = pixels.length;
    for (int i = 0; i < rows; i++) {
        if (maxCount < pixels[i].length) {
            maxCount = pixels[i].length;
        }
    }
    return maxCount;
}

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.