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.
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.
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.
Well, there are a couple of workarounds. You mentioned one yourself. Another one would be:
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.
Java has no equivalent of C++ references. The only way to get this to work is to encapsulate the values in another class and swap the values within the class.
Here is a lengthy discussion on the issue: http://www.yoda.arachsys.com/java/passing.html
Java passes parameters by value, and has no mechanism to allow pass-by-reference.