Reputation: 33
I really need to explain behavior of code I have created.
Variable preyPred here: private static double[] preyPredLV(double[] preyPred, double[] a, double[] b, int n)
is local for method preyPredLV or not?
Because, when I manipulate it during calling of the method, and then I call the method again for different n, it does not assign preyPredDefault as value of preyPred, but it uses its own value from previous call. Shouldn't its previous value be discarded when method returns output value and shouldn't be the new value assigned during next call? Can someone please explain? Thank you
Whole code:
public class Main {
public static void main(String[] args) {
double[] preyPredDefault = {300, 20};
double[] a = {0.1, 0.01};
double[] b = {0.01, 0.00002};
int n = 1;
double[] result = preyPredLV(preyPredDefault, a, b, n);
System.out.println("After "+n+" generations: Hares = "+result[0]+" and Lynx = "+result[1]);
n = 2;
result = preyPredLV(preyPredDefault, a, b, n);
System.out.println("After "+n+" generations: Hares = "+result[0]+" and Lynx = "+result[1]);
}
private static double[] preyPredLV(double[] preyPred, double[] a, double[] b, int n) {
double[] preyPredOld = new double[2];
System.out.println("n = "+n);
System.out.println("preyPred[0] = "+preyPred[0]);
System.out.println("preyPred[1] = "+preyPred[1]);
for(int iteration = 0; iteration < n; iteration++){
preyPredOld[0] = preyPred[0];
preyPredOld[1] = preyPred[1];
preyPred[0] = preyPredOld[0] * (1 + a[0] - a[1]*preyPredOld[1]);
preyPred[1] = preyPredOld[1] * (1 - b[0] + b[1]*preyPredOld[0]);
}
return preyPred;
}
}
Result:
n = 1
preyPred[0] = 300.0
preyPred[1] = 20.0
After 1 generations: Hares = 270.00000000000006 and Lynx = 19.92
n = 2
preyPred[0] = 270.00000000000006
preyPred[1] = 19.92
After 2 generations: Hares = 219.31183648512007 and Lynx = 19.726535847029762
Upvotes: 3
Views: 124
Reputation: 262464
Arrays in Java are not passed as a copy. They are passed as a reference to the array, which is then shared between caller and method.
So if you update the array from within the method, this is an in-place update, and the changes will be visible to whoever else has a reference to that array.
If you want to avoid that, make a "defensive copy" (using Arrays.copyOf) and make changes only to that.
Upvotes: 4
Reputation: 393771
You are passing a reference of the preyPredDefault
array to your preyPredLV
method, and your method updates this array via the reference you pass. Thus your method modifies the content of that array.
If you don't want preyPredLV
to update that array, you can pass it a copy of the array.
double[] result = preyPredLV(Arrays.copyOf(preyPredDefault,preyPredDefault.length), a, b, n);
Upvotes: 2