Java return two variables from one method

Posted in :

How to write the following code correctly?

public String toString(int[] position, int xOffset, int yOffset) {
    String postn = String.format("[%d,%d]", position[0], position[1]);
    String movm = String.format("[%d,%d]", xOffset, yOffset);

    return (postn, movm);
}


 

When using Java 8 you could make use of the Pair class.

private static Pair<String, String> foo (/* some params */) {
    final String val1 = "";  // some calculation
    final String val2 = "";  // some other calculation

    return new Pair<>(val1, val2);
}

Otherwise simply return an array.


Instead of returning an array that contains the two values or using a generic Pair class, consider creating a class that represents the result that you want to return, and return an instance of that class. Give the class a meaningful name. The benefits of this approach over using an array are type safety and it will make your program much easier to understand.

Note: A generic Pair class, as proposed in some of the other answers here, also gives you type safety, but doesn’t convey what the result represents.

Example (which doesn’t use really meaningful names):

final class MyResult {
    private final int first;
    private final int second;

    public MyResult(int first, int second) {
        this.first = first;
        this.second = second;
    }

    public int getFirst() {
        return first;
    }

    public int getSecond() {
        return second;
    }
}

// ...

public static MyResult something() {
    int number1 = 1;
    int number2 = 2;

    return new MyResult(number1, number2);
}

public static void main(String[] args) {
    MyResult result = something();
    System.out.println(result.getFirst() + result.getSecond());
}

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *