通过引用传递和递归

Cod*_*lus 5 java parameters methods parameter-passing

我有以下递归函数原型:

public void calcSim(Type<String> fort, Integer metric)
   Integer metric = 0;
   calcSim(fort, metric);
   System.out.println("metric: " + metric);
}
Run Code Online (Sandbox Code Playgroud)

我想打印度量值,如上所示.但它始终为零.现在,当我在函数结束时打印时,我得到一个有效的数字.

  1. 如何通过引用传递或获得与C++相同的功能
  2. 关于参数传递,我该怎么办?(按价值,参考等等......)

Aff*_*ffe 7

没有像Java那样的引用,抱歉:(

您可以选择为方法提供返回值,也可以使用可变包装器并随时设置值.使用AtmoicInteger导致它在JDK中,使你自己不担心线程安全当然会稍微快一些.

AtomicInteger metric = new AtomicInteger(0);
calcSim(fort, metric);
System.out.println("metric: " + metric.get());
Run Code Online (Sandbox Code Playgroud)

然后在calcSim中设置它 metric.set(int i);


Kep*_*pil 5

要获得通过引用传递的行为,您可以创建一个包装类,并在该类中设置值,例如:

class MyWrapper {
    int value;
}
Run Code Online (Sandbox Code Playgroud)

然后您可以将 a 传递MyWrapper给您的方法并更改值,例如:

public void calcSim(Type<String> fort, MyWrapper metric)
   metric.value++;
   System.out.println("metric: " + metric.value);
   calcSim(fort, metric);
}
Run Code Online (Sandbox Code Playgroud)