How do I use an equivalent to C++ reference parameters in Java?
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.
Simulating reference with wrappers.
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
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.
链接地址: http://www.djcxy.com/p/20708.html上一篇: 线程之间是否共享静态变量?