Suppose I have this in C++:
void test(int &i, int &j)
{
++i;
++j;
}
The values are altered inside the function and then use
Java passes parameters by value, and has no mechanism to allow pass-by-reference.
One way you can have this behavior somehow simulated is create a generic wrapper.
public class _<E> {
E ref;
public _( E e ){
ref = e;
}
public E g() { return ref; }
public void s( E e ){ this.ref = e; }
public String toString() {
return ref.toString();
}
}
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:
public class Test {
public static void main ( String [] args ) {
_<Integer> iByRef = new _<Integer>( 1 );
addOne( iByRef );
System.out.println( iByRef ); // prints 2
_<String> sByRef = new _<String>( "Hola" );
reverse( sByRef );
System.out.println( sByRef ); // prints aloH
}
// Change the value of ref by adding 1
public static void addOne( _<Integer> ref ) {
int i = ref.g();
ref.s( ++i );
// or
//int i = ref.g();
//ref.s( i + 1 );
}
// Reverse the vale of a string.
public static void reverse( _<String> otherRef ) {
String v = otherRef.g();
String reversed = new StringBuilder( v ).reverse().toString();
otherRef.s( reversed );
}
}
The amusing thing here, is the generic wrapper class name is "_" which is a valid class identifier. So a declaration reads:
For an integer:
_<Integer> iByRef = new _<Integer>( 1 );
For a String:
_<String> sByRef = new _<String>( "Hola" );
For any other class
_<Employee> employee = new _<Employee>( Employee.byId(123) );
The methods "s" and "g" stands for set and get :P
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
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.
class A{
public void test(Coord c)
{
c.x++;
c.y++;
}
private class Coord{
public int x, y;
}
}
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.
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.