我正在尝试为树提供一个 void 函数。它计算一些参数并使用Id来引用一些坐标以及它们之间的距离。我遇到的问题是,每次递归调用都会在我使用的两个参数上返回 0,我认为在 Java 中每个变量都是一个引用,所以这可以工作,但我似乎遗漏了一些东西。这是代码:
public void volumeandcost(Integer volume,Float cost){
if(children().equals(0)){//children() returns the number of children our tree has
volume=volume+getCapacidad(this.root);//root is the Id
}
else{//recursive call
ArrayList<Integer> myvol= new ArrayList();
ArrayList<Float> mycost=new ArrayList();
for(int i=0;i<this.children();i++){
myvol.add(new Integer(0));
mycost.add(new Float(0.0));
children.get(i).volumeandcost(myvol.get(i), mycost.get(i));
cost=cost+mycost.get(i)+myvol.get(i)*
square(ProbIA5Board.m_dist.get(this.root).get(this.children.get(i).getId()));
}
//this calculates our volume in case we have children
volume=min(getCapacidad(root)*3,mysum(myvol)+getCapacidad(root));
}
}
我调用此函数时,两个参数最初都设置为 0,并且在调用volumeandcost 后它们以相同的方式返回。
遵循一些建议后,我实现了一个新的类 Pair,如下所示:
public class Pair {
Integer vol;Float cost;
public Pair (){this.vol=new Integer(0);this.cost=new Float(0);}
Integer getVol(){ return this.vol;}
Float getCost(){ return this.cost;}
void setVol(Integer x){this.vol=x ;}
void setCost(Float x){this.cost=x ;}
void addVol(Integer x){this.vol=this.vol+x;}
void addCost(Float x){this.cost=this.cost+x;}
}
并修改了函数,使其如下所示:
public void volumeandcostp(Pair p){
if(children().equals(0)){
p.setVol(p.getVol() + getCapacidad(this.root));//tenemos el volumen
}
else{//recursion
ArrayList<Pair> myvol= new ArrayList();
for(int i=0;i<this.children();i++){
myvol.add(new Pair());
children.get(i).volumeandcostp(myvol.get(i));
myvol.get(i).getCost());
p.addCost(myvol.get(i).getCost()+ myvol.get(i).getVol()* square(ProbIA5Board.m_dist.get(this.root).get(this.children.get(i).getId())));
} p.setVol(min(getCapacidad(root)*3,mysump(myvol)+getCapacidad(root)));
}
}
但是 Pair 中的所有 getter 一直给我 0 作为答案。
最佳答案
I thought in Java every variable was a reference.
首先,这个说法错误:你有 primitive types如int
、float
、char
。首先,这些不是引用。但实际上,除了这八种类型之外的变量都是引用。
但是当您调用函数时,Java 会执行按值调用。这意味着引用被复制。当您调用:volumeandcost(a,b)
。 Java 将复制该引用。因此,数量
和成本
独立工作。 在您的方法中设置它们(即为它们分配新值)没有任何效果。
您可以更改给定对象的状态:因为您复制引用a
引用了相同的对象作为volume
(在上面的示例中),您可以调用引用引用的对象上的方法并更改状态,但您无法更改引用本身。
关于Java树递归参数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43126246/