gpt4 book ai didi

java - 如何在 Java 中对原语执行相当于引用传递的操作

转载 作者:行者123 更新时间:2023-11-30 16:13:07 25 4
gpt4 key购买 nike

这段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  

In C++ I can pass the toyNumber variable as pass by reference to avoid shadowing i.e. creating a copy of the same variable as below:

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 is pass by value rather than pass by reference 获得与 C++ 代码相同的输出,Java 中的等效代码是什么? ?

最佳答案

您有多种选择。最有意义的实际上取决于您想要做什么。

选择 1:将 toyNumber 设为类中的公共(public)成员变量

class MyToy {
public int toyNumber;
}

然后将对 MyToy 的引用传递给您的方法。

void play(MyToy toy){  
System.out.println("Toy number in play " + toy.toyNumber);
toy.toyNumber++;
System.out.println("Toy number in play after increement " + toy.toyNumber);
}

选择 2:返回值而不是通过引用传递

int play(int toyNumber){  
System.out.println("Toy number in play " + toyNumber);
toyNumber++;
System.out.println("Toy number in play after increement " + toyNumber);
return toyNumber
}

此选择需要对 main 中的调用站点进行一些小更改,以便其显示为 toyNumber = temp.play(toyNumber);

选择 3:将其设为类或静态变量

如果这两个函数是同一类或类实例上的方法,您可以将 toyNumber 转换为类成员变量。

选择 4:创建一个 int 类型的单元素数组并传递该数组

这被认为是一种黑客行为,但有时用于从内联类调用返回值。

void play(int [] toyNumber){  
System.out.println("Toy number in play " + toyNumber[0]);
toyNumber[0]++;
System.out.println("Toy number in play after increement " + toyNumber[0]);
}

关于java - 如何在 Java 中对原语执行相当于引用传递的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58150589/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com