[英]Passing an object as a parameter in Java
There is a scenario有一个场景
Say I have a class People
& a utility class PeopleUtil
with a method computeTotalNumberOfPeople
假设我有一个类
People
和一个实用类PeopleUtil
其中有一个方法computeTotalNumberOfPeople
In a separate class say EvaluatePeople
where I have code在一个单独的课程中说
EvaluatePeople
我有代码
People people = new People();
people.setValue(10);
people.setX(45);
PeopleUtil.computeTotalNumberOfPeople(people);
this.persistPeople(people);
In the computeTotalNumberOfPeople
method在
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);
}
When I look at the People object in the db row I see the totalNumberOfPeople
value persisted.当我查看 db 行中的 People 对象时,我看到
totalNumberOfPeople
值仍然存在。 Which is actually fine.这实际上很好。
My question is, I am a little confused about it, shouldn't computeTotalNumberOfPeople
method return the people object, which has an extra set value, to the method caller code & then that object should be passed to the peristPeople method as an argument?我的问题是,我对此有点困惑,
computeTotalNumberOfPeople
方法不应该将具有额外设置值的 people 对象返回给方法调用者代码,然后将该对象作为参数传递给 peristPeople 方法吗?
I hope you understand what I mean, it doesn't seem right someway我希望你明白我的意思,这似乎有点不对
Objects are mutable – they can be changed.对象是可变的——它们可以改变。
So when you call people.setTotalNumberOfPeople(totalPeople)
, you are setting the totalNumberOfPeople
variable (or whatever it's called inside the People
class) to totalPeople
for the people
object.所以,当你调用
people.setTotalNumberOfPeople(totalPeople)
您正在设置totalNumberOfPeople
变量(或任何它被称为内部People
类) totalPeople
的people
反对。
When you exit the computeTotalNumberOfPeople
method, the object is still the same one that was modified – the changes from the method persist.当您退出
computeTotalNumberOfPeople
方法时,该对象仍然是修改过的对象——方法中的更改仍然存在。
One way to think about it is passing a reference to people
.考虑它的一种方法是将引用传递给
people
。 When you call computeTotalNumberOfPeople(people)
, you are passing a reference to people
.当您调用
computeTotalNumberOfPeople(people)
,您传递的是对people
的引用。 When people
is modified, you modifying the same location in memory, and so the changes persist.当
people
被修改时,您会修改内存中的相同位置,因此更改会持续存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.