假设我在C++中有这个:
void test(int &i, int &j)
{
++i;
++j;
}
Run Code Online (Sandbox Code Playgroud)
在函数内部更改值,然后在外部使用.我怎么能写一个在Java中做同样的代码?我想我可以返回一个封装两个值的类,但这看起来真的很麻烦.
Osc*_*Ryz 18
以某种方式模拟这种行为的一种方法是创建一个通用的包装器.
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();
}
}
Run Code Online (Sandbox Code Playgroud)
我不太相信这段代码的价值,我无法帮助它,我不得不编码:)
所以这就是.
样本用法:
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 );
}
}
Run Code Online (Sandbox Code Playgroud)
这里有趣的是,通用包装类名是"_",它是一个有效的类标识符.声明如下:
对于整数:
_<Integer> iByRef = new _<Integer>( 1 );
Run Code Online (Sandbox Code Playgroud)
对于字符串:
_<String> sByRef = new _<String>( "Hola" );
Run Code Online (Sandbox Code Playgroud)
对于任何其他类
_<Employee> employee = new _<Employee>( Employee.byId(123) );
Run Code Online (Sandbox Code Playgroud)
方法"s"和"g"代表set和get:P
Jar*_*Par 13
Java没有相当于C++的引用.使其工作的唯一方法是将值封装在另一个类中并交换类中的值.
以下是对该问题的冗长讨论:http://www.yoda.arachsys.com/java/passing.html
好吧,有几个解决方法.你自己提到了一个.另一个是:
public void test(int[] values) {
++values[0];
++values[1];
}
Run Code Online (Sandbox Code Playgroud)
不过,我会选择自定义对象.这是一种更清洁的方式.此外,尝试重新排列您的问题,以便单个方法不需要返回两个值.