如何在Java中执行等效的按引用传递

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

回答:

你有几种选择。最有意义的选择实际上取决于你要执行的操作。

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

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的单个元素数组,然后传递该数组

这被认为是一种hack,但有时可用于从内联类调用中返回值。

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中执行等效的按引用传递 的全部内容, 来源链接: utcz.com/qa/407524.html

回到顶部