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.

halfer
  • 19,824
  • 17
  • 99
  • 186
pitosalas
  • 10,286
  • 12
  • 72
  • 120

3 Answers3

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};
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
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.

corsiKa
  • 81,495
  • 25
  • 153
  • 204
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.

Community
  • 1
  • 1
n0rm1e
  • 3,796
  • 2
  • 28
  • 37
  • 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? – pitosalas Sep 23 '11 at 15:39
  • This way you don't need to worry about accessing an element in an index out of bound 0-1. – n0rm1e Sep 24 '11 at 02:06