gpt4 book ai didi

java - 在 Java 中将对象作为参数传递

转载 作者:行者123 更新时间:2023-11-30 08:35:17 25 4
gpt4 key购买 nike

有一个场景

假设我有一个类 People 和一个实用程序类 PeopleUtil 以及一个方法 computeTotalNumberOfPeople

在一个单独的类中说EvaluatePeople 我有代码

People people = new People();
people.setValue(10);
people.setX(45);
PeopleUtil.computeTotalNumberOfPeople(people);
this.persistPeople(people);

computeTotalNumberOfPeople 方法中

public void computeTotalNumberOfPeople(People people){
//logic for computing total no of people & then
int totalPeople = certainIntValue;
// I can return the totalPeople value from this method but I am not doing it just for the sake of this scenario
people.setTotalNumberOfPeople(totalPeople);
}

当我查看数据库行中的 People 对象时,我看到 totalNumberOfPeople 值一直存在。这实际上很好。

我的问题是,我对此有点困惑,computeTotalNumberOfPeople 方法不应该将具有额外设置值的 people 对象返回给方法调用者代码,然后该对象应该是作为参数传递给 peristPeople 方法?

我希望你能明白我的意思,好像不太对

最佳答案

对象是可变的——它们可以被改变。

因此,当您调用 people.setTotalNumberOfPeople(totalPeople) 时,您正在设置 totalNumberOfPeople 变量(或在 People 类中调用的任何内容) 到 totalPeoplepeople 对象。

当您退出 computeTotalNumberOfPeople 方法时,对象仍然是被修改的那个对象——方法的更改仍然存在。

考虑它的一种方法是传递对people 的引用。当您调用 computeTotalNumberOfPeople(people) 时,您正在将 reference 传递给 people。当修改 people 时,您修改的是内存中的相同位置,因此更改会持续存在。

关于java - 在 Java 中将对象作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38283790/

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