Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#'s ref and out in Java

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?

like image 586
Tarik Avatar asked Dec 12 '10 19:12

Tarik


2 Answers

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:

  • arrays: simple vs. ugly, relies on array having exactly one element
  • holder: safe vs. verbose, boxing
  • purpose-built type: safe vs. verbose, possible overkill
  • change method: safe, clean vs. not always possible

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. :)

like image 152
WReach Avatar answered Sep 27 '22 18:09

WReach


Java does not support this feature.

like image 40
SLaks Avatar answered Sep 27 '22 16:09

SLaks