Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass by Reference and recursion

I have the following recursive function prototype:

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

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

  1. How do I pass by reference or get the equivalent functionality like in C++
  2. What all can I do with regards to my parameter passing? (by value, by reference, etc...)
like image 761
CodeKingPlusPlus Avatar asked Oct 19 '12 20:10

CodeKingPlusPlus


Video Answer


4 Answers

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

Your options are either to give the method a return value, or use a mutable wrapper and set the value as you go. Using AtmoicInteger cause it is in JDK, making your own that doesn't worry about threadsafety would of course be mildly faster.

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

Then inside the calcSim set it with metric.set(int i);

like image 89
Affe Avatar answered Oct 07 '22 08:10

Affe


To get the behavior of pass by reference, you can create a wrapper class, and set the value in that class, eg:

class MyWrapper {
    int value;
}

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

public void calcSim(Type<String> fort, MyWrapper metric)
   metric.value++;
   System.out.println("metric: " + metric.value);
   calcSim(fort, metric);
}
like image 29
Keppil Avatar answered Oct 07 '22 07:10

Keppil


Integer is wrapper class. Wrapper classes are immutable. So, what you are expecting can't be achieved with Integer type.

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

like image 2
kosa Avatar answered Oct 07 '22 09:10

kosa


Two big issues:

  1. You are redefining metric with the same name in your method as well. How is program printing anything. It should complain at compilation time.

  2. No defined exit criteria. Does you program(method) stops?

I think you wanted something as (pseudo code as I don't know what are you 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);
   }
 }
like image 1
Yogendra Singh Avatar answered Oct 07 '22 07:10

Yogendra Singh