Suppose I have this in C++:
void test(int &i, int &j)
{
++i;
++j;
}
The values are altered inside the function and then used outside. How could I write a code that does the same in Java? I imagine I could return a class that encapsulates both values, but that seems really cumbersome.
Are the two integers related? Like a pair of x/y coordinates? If so, I would put the integers in a new class and pass that class into the method.
If the two integers are not related, you might want to think about why you are passing them into the same method in the first place.
Though its a bad design pattern IMHO, Another possible solution is
The easiest solution is to use org.apache.commons.lang.mutable.MutableInt class you don't need to write by yourself.
Simulating reference with wrappers.
One way you can have this behavior somehow simulated is create a generic wrapper.
I'm not too convinced about the value of this code, by I couldn't help it, I had to code it :)
So here it is.
The sample usage:
The amusing thing here, is the generic wrapper class name is "_" which is a valid class identifier. So a declaration reads:
For an integer:
For a String:
For any other class
The methods "s" and "g" stands for set and get :P
You have to box it (your way) somehow.
Integer is immutable. so useless. int is mutable but since java is pass by value then its unusable again in that case. See these pages for more explanations: Java is Pass-by-Value, Dammit! and int vs Integer
Apache commons lang has a MutableInt class. Or you could write it yourself.
In any case, it should not be that bad because it should not happen often. If it does, then you should definitively change the way you code in Java.
You could construct boxed objects, ie,
and write your routine as
For any number of reasons, the designers of Java felt call-by-value was better; they purposefully didn't include a method for call by reference. (Strictly, they pass copies of references to the objects, with the special case for the primitive types that they are purely call by value. But the effect is the same.)