As we know both language are pass-by-value when passing parameters to methods. But C# supports ref
and out
keywords to pass-by-reference of primitive types. I am looking for the same keywords and technique in Java?
My guess is using Integer
wrapper class instead of int
in Java to pass in.
Any suggestions and examples?
Your guess is correct. A wrapper is needed (but not Integer as it is immutable).
Some people use single element arrays for this purpose:
int[] x = { 0 };
int[] y = { 0 };
someMethod(x, y);
return x[0] + y[0];
Many will rank that technique right up there with GOTO.
Some people define a generic holder class:
public class Holder<T> {
private T _value;
private Holder(T value) { _value = value; }
public static of(T value) { return new Holder<T>(value); }
public T getValue() { return _value; }
public void setValue(T value) { _value = value; }
}
...
Holder<String> x = Holder.of("123");
Holder<String> y = Holder.of("456");
someMethod(x, y);
return x.getValue() + y.getValue();
Some define a purpose-built type:
SomeMethodResult result = someMethod(x, y);
return result.getX() + result.getY();
Some would arrange for the work to be done inside the method, avoiding the need for by-reference arguments in the first place:
return someMethod(x, y);
Each of these techniques has advantages and disadvantages:
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. :)
Java does not support this feature.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With