0

I am trying to return two numbers from this method. I thought this was correct. Where am I going wrong?

public int[] getDimension() {
    int shapeWidth = 0;
    int shapeHeight = 0;
// .....
    int[] result = new int[] {shapeWidth, shapeHeight};
    return result;
}

And then at a calling site, is this correct?

  public int getWidth() {
      return getDimension()[0];
  } 

I am asking because I believe there's a bug but I don't see it.

3 Answers 3

4

That's fine. Short but complete program to demonstrate it working:

public class Test {

    public static void main(String args[]) {
        int width = getDimension()[0];
        System.out.println(width);
    }

    public static int[] getDimension() {
        int shapeWidth = 5;
        int shapeHeight = 10;
        int[] result = new int[] {shapeWidth, shapeHeight};
        return result;
    }
}

You can make the result declaration line slightly simpler, by the way:

int[] result = {shapeWidth, shapeHeight};
Sign up to request clarification or add additional context in comments.

Comments

3

Rather than using an array, I would recommend using a class

class Dimensions {
    private int width;
    private int height;

    public Dimensions(int width, int height) {
        this.width = width;
        this.height = height;
    }

    // add either setters and getters
    // or better yet, functionality methods instead
}

This will give you compile time referential integrity, which is much better than inferring based on "we know index 0 is width and index 1 is height".

If you still want to use an array, Jon's answer is spot on.

Comments

1

Your code looks fine, but try not to use an array if you only need a pair.

Since Java doesn't have tuples/pairs you have to implement them, but it's pretty easy. Refer to this question for a possible implementation.

public class Test {

    public static void main(String args[]) {
        int width = getDimension().getLeft();
        System.out.println(width);
    }

    public static Pair<Integer, Integer> getDimension() {
        int shapeWidth = 5;
        int shapeHeight = 10;
        return new Pair<Integer, Integer>(shapeWidth, shapeHeight);
    }
}

This is better than a Dimension class, because you can use it everywhere in your code.

2 Comments

Interesting... the reason you like this better is that it 'documents' that the array must only have 2 elements? It's an interesting tradeoff because on the other hand you now have one more class to deal with. Or is your feeling more about performance?
This way you don't need to worry about accessing an element in an index out of bound 0-1.

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.