5

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...)
Yogendra Singh
  • 33,927
  • 6
  • 63
  • 73
CodeKingPlusPlus
  • 15,383
  • 51
  • 135
  • 216

4 Answers4

9

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);

Affe
  • 47,174
  • 11
  • 83
  • 83
5

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);
}
Keppil
  • 45,603
  • 8
  • 97
  • 119
2

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.

kosa
  • 65,990
  • 13
  • 130
  • 167
1

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);
   }
 }
Yogendra Singh
  • 33,927
  • 6
  • 63
  • 73