Returning Multiple Values from Java Methods
Returning multiple values from a Java method presents a challenge if traditional methods are used. Attempting to return two values as demonstrated in the code below will result in a compilation error.
<code class="java">public static int something() { int number1 = 1; int number2 = 2; return number1, number2; // Compilation error: cannot return multiple values }</code>
Overcoming the Limitation
To resolve this limitation, consider using a custom class to represent the result, rather than returning an array or using a generic Pair class. This approach not only ensures type safety, but also enhances code readability.
Example Implementation
<code class="java">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()); }</code>
The above is the detailed content of How can I return multiple values from a Java method?. For more information, please follow other related articles on the PHP Chinese website!