Return Two and More Values from a Method

How to return 2 values from a Java method?

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

Return multiple values to a method caller

In C# 7 and above, see this answer.

In previous versions, you can use .NET 4.0+'s Tuple:

For Example:

public Tuple<int, int> GetMultipleValue()
{
return Tuple.Create(1,2);
}

Tuples with two values have Item1 and Item2 as properties.

Return multiple values from function

Dart doesn't support multiple return values.

You can return an array,

List foo() {
return [42, "foobar"];
}

or if you want the values be typed use a Tuple class like the package https://pub.dartlang.org/packages/tuple provides.

See also either for a way to return a value or an error.



Related Topics



Leave a reply



Submit