Pass Parameter In Array

JavaPassesByValue, but sometimes you want PassByReference.

Therefore: Pass the parameter wrapped in an array:

  void addOne (int[] arg)
    {
    arg [0] = arg [0] + 1;
    }

...

int a[] = {2}; addOne (a); System.out.println (a [0] );

3

However: This smells funny, so see AlternativesToPassByReference

See also: PassParameterInWrapperObject


Since arrays are just special types of Objects in Java if pass-by-reference is important then:

 void addOne(Integer i) { ... }

Seems to make the intent much clearer and autoboxing/unboxing in 1.5 makes working with the primitive boxing classes less of a hassle. I don't quite get the point of PassParameterInWrapperObject in this case - all the wrappers you need are already there! Not only that but you're wasting at least one extra integer as arrays pass their size around with them (the final int length field). -- JamesHollidge


Integer is an immutable type. So your example won't work; any changes you make to i won't be reflected when you exit the method.


CategoryJava


EditText of this page (last edited April 1, 2008) or FindPage with title or text search