Suppose I have this in C++:
void test(int &i, int &j)
{
++i;
++j;
}
The values are altered inside the function and then use
The easiest solution is to use org.apache.commons.lang.mutable.MutableInt class you don't need to write by yourself.
A better question: why are you creating methods with such side-effects?
Generally, this is a strong indication that you should extract the data into a separate class, with public accessors that describe why the operation is taking place.
Though its a bad design pattern IMHO, Another possible solution is
static void test(AtomicInteger i, AtomicInteger j)
{
i.incrementAndGet();
j.incrementAndGet();
}
Well, there are a couple of workarounds. You mentioned one yourself. Another one would be:
public void test(int[] values) {
++values[0];
++values[1];
}
I would go with the custom object, though. It’s a much cleaner way. Also, try to re-arrange your problem so that a single method doesn’t need to return two values.
You could construct boxed objects, ie,
Integer iObj = new Integer(i);
Integer jObj = new Integer(j);
and write your routine as
public void test(Integer i, Integer j){
i = i.add(1);
j = j.add(1);
}
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.)
Java does not have pass-by-reference. You must encapsulate to achieve the desired functionality. Jon Skeet has a brief explanation why pass-by-reference was excluded from Java.