pitosalas
pitosalas

Reputation: 10852

Returning an array from a Java method

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.

Upvotes: 0

Views: 175

Answers (3)

n0rmzzz
n0rmzzz

Reputation: 3848

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.

Upvotes: 1

corsiKa
corsiKa

Reputation: 82559

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.

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1500055

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};

Upvotes: 4

Related Questions