Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Your guess is correct. A wrapper is needed (but not Integer as it is immutable).</p> <p>Some people use single element arrays for this purpose:</p> <pre><code>int[] x = { 0 }; int[] y = { 0 }; someMethod(x, y); return x[0] + y[0]; </code></pre> <p>Many will rank that technique right up there with GOTO.</p> <p>Some people define a generic holder class:</p> <pre><code>public class Holder&lt;T&gt; { private T _value; private Holder(T value) { _value = value; } public static of(T value) { return new Holder&lt;T&gt;(value); } public T getValue() { return _value; } public void setValue(T value) { _value = value; } } ... Holder&lt;String&gt; x = Holder.of("123"); Holder&lt;String&gt; y = Holder.of("456"); someMethod(x, y); return x.getValue() + y.getValue(); </code></pre> <p>Some define a purpose-built type:</p> <pre><code>SomeMethodResult result = someMethod(x, y); return result.getX() + result.getY(); </code></pre> <p>Some would arrange for the work to be done inside the method, avoiding the need for by-reference arguments in the first place:</p> <pre><code>return someMethod(x, y); </code></pre> <p>Each of these techniques has advantages and disadvantages:</p> <ul> <li>arrays: simple vs. ugly, relies on array having exactly one element</li> <li>holder: safe vs. verbose, boxing</li> <li>purpose-built type: safe vs. verbose, possible overkill</li> <li>change method: safe, clean vs. not always possible</li> </ul> <p>Personally, I think that Java messed up on this one. I'd rather avoid by-reference arguments, but I wish Java permitted multiple return values from a method. But, truthfully, I don't trip over this one very often. I wouldn't give a kidney for this feature. :)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload