My function takes as input two Double objects, and I would like to modify them both inside the function. It seems it is not possible, it seems java copies them inside the function. How is this done in java, in c++ you pass by reference.
Thanks
My function takes as input two Double objects, and I would like to modify them both inside the function. It seems it is not possible, it seems java copies them inside the function. How is this done in java, in c++ you pass by reference.
Thanks
Wrapper classes are immutable, that is the reason you were unable to modify them. One way is , you may create one class with these two attributes and pass it to the function, inside function, set new values to that object.
What you can do is wrap the Double
objects into a Wrapper class, and modify the doubles stored in that object.
Otherwise, no other way, as the only value you will change is the local argument.
public class DoubleWrapper
{
private double d1, d2;
public void setter(double newdouble){}
public double getter() {}
}
Pass the double values in an array, you can modify array elements in your function.
Java is call by value, so you're right: It must be done in another manner.
There are two issues here:
First, all values in Java are pass-by-value. This means that, when an object X is sent to a function, that function holds a new version of X.
Second, you can't modify a Double
value. You have to modify a double
, and can convert from Double d
to double
by running d.doubleValue()
.
In general you shouldn't be modifying arguments in Java (or perhaps any language)
Instead I suggest you return the values changed as an array
public static double[] square(double... doubles) {
double[] ret = new double[doubles.length];
for(int i = 0; i < doubles.length; i++)
ret[i] = doubles[i] * doubles[i];
return ret;
}
Ideally, you would have a class which wraps these doubles and you call a method to alter them
class MyDoubles {
double d1, d2;
public void squareDoubles() {
d1 *= d1;
d2 *= d2;
}
public String toString() { return "{ " + d1 +", " + d2 + "}"; }
}