Link and recursion

I have the following prototype of a recursive function:

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

I want to print the metric value as shown above. However, it is always zero. Now, when I type at the end of the function, I get a real number.

  • How to pass a link or get equivalent functionality, for example, in C ++
  • What can I do regarding the transfer of my parameter? (by value, by reference, etc.)
+4
source share
4 answers

There is no such thing as passing by reference in Java, sorry :(

Your options are either to give the method a return value, or use a mutable shell and set the value as you move. Using AtmoicInteger results in it being in the JDK, so your own, which doesn't care about thread safety, will of course be moderately faster.

 AtomicInteger metric = new AtomicInteger(0); calcSim(fort, metric); System.out.println("metric: " + metric.get()); 

Then inside calcSim, install it using metric.set(int i);

+5
source

To get pass by reference behavior, you can create a wrapper class and set a value in this class, for example:

 class MyWrapper { int value; } 

Then you can pass MyWrapper to your method and change the value, for example:

 public void calcSim(Type<String> fort, MyWrapper metric) metric.value++; System.out.println("metric: " + metric.value); calcSim(fort, metric); } 
+3
source

Integer is a wrapper class. The wrapper classes are immutable. So, what you expect cannot be achieved with the Integer type.

You can create a mutable wrapper class around the primitive and update the object to achieve what you want.

+1
source

Two big problems:

  • You override metric with the same name in your method. How the program prints anything. He must complain about compilation time.

  • No exit criteria defined. Are you stopping the program (method)?

I think you wanted something like (pseudocode, since I don't know what you are doing):

  public void calcSim(Type<String> fort, Integer metric) if(condtion){ //print or return }else{ //modify fort or metric so that it exits calcSim(fort, metric); //call this with modified value System.out.println("metric: " + metric.value); } } 
+1
source

Source: https://habr.com/ru/post/1440874/


All Articles