如何在 Java 中对基元执行通过引用传递的等效操作
2022-08-31 08:41:30
此 Java 代码:
public class XYZ {
public static void main(){
int toyNumber = 5;
XYZ temp = new XYZ();
temp.play(toyNumber);
System.out.println("Toy number in main " + toyNumber);
}
void play(int toyNumber){
System.out.println("Toy number in play " + toyNumber);
toyNumber++;
System.out.println("Toy number in play after increement " + toyNumber);
}
}
将输出以下内容:
Toy number in play 5 Toy number in play after increement 6 Toy number in main 5
在C++我可以将变量作为传递引用传递,以避免阴影,即创建同一变量的副本,如下所示:toyNumber
void main(){
int toyNumber = 5;
play(toyNumber);
cout << "Toy number in main " << toyNumber << endl;
}
void play(int &toyNumber){
cout << "Toy number in play " << toyNumber << endl;
toyNumber++;
cout << "Toy number in play after increement " << toyNumber << endl;
}
C++输出将是这样的:
Toy number in play 5 Toy number in play after increement 6 Toy number in main 6
我的问题是 - Java中的等效代码是什么,以获得与C++代码相同的输出,因为Java是按值传递而不是通过引用传递的?