在Java中作为参数传递对象
有一种情况 假设我有一个类在Java中作为参数传递对象,java,Java,有一种情况 假设我有一个类People&一个实用类PeopleUtil,方法是computeTotalNumberOfPeople 在一个单独的类中,说EvaluatePeople我有代码的地方 People people = new People(); people.setValue(10); people.setX(45); PeopleUtil.computeTotalNumberOfPeople(people); this.persistPeople(people); 在compute
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);
}
当我查看db行中的People对象时,我看到totalNumberOfPeople
值保持不变。这其实很好
我的问题是,我对此有点困惑,computeTotalNumberOfPeople
method是否应该将具有额外设置值的people对象返回给方法调用方代码&然后该对象应该作为参数传递给peristPeople方法
我希望你能理解我的意思,在某种程度上它似乎不正确。对象是可变的,它们可以改变 因此,当您调用
people.setTotalNumberOfPeople(totalPeople)
时,您将totalNumberOfPeople
变量(或在people
类中调用的任何变量)设置为totalPeople
对象的totalPeople
当您退出computeTotalNumberOfPeople
方法时,对象仍然是修改过的对象–该方法的更改仍然存在
思考这个问题的一种方法是将引用传递给
人
。调用computeTotalNumberOfPeople(people)
时,您正在传递对people
的引用。当修改people
时,您将修改内存中的相同位置,因此更改将保持不变。您只将对象引用传递给方法调用。因此,您在每个方法中都对同一对象进行操作。因此,返回对象是不必要的。您可以修改方法以返回给定的people
对象,这在主观上确实可以使代码在这种情况下更容易理解(取决于个人意见)。这不是技术上必需的,因为对象是通过引用传递的,因此对由该变量引用的对象的任何修改都会反映在引用该对象相同实例的任何其他变量中。作为一般性注释,我认为SET是一个错误的实践。您希望您的类尽可能不可变,否则跟踪它们的状态可能很棘手,因为CodeBender和David是正确的。您可能应该花一些时间阅读关于传递值和传递引用之间的差异。下面是一个很好的例子,它解释了Java如何实现数据到方法的传递。不过,副作用方法在Java中并不特别惯用。我只需返回总人数,让打电话的人决定如何处理。它更灵活、更惯用,并且是一种更清晰的关注点分离