简体   繁体   中英

Java array values being put into wrong array

The following code runs once through the loop fine, but on the second pass, theEquation has had its data changed even though nothing had referenced it.

String[] theEquation = breakdown(theequation);
double[] yValues = new double[400];

for(int i=0; i < bitmapx; i++){
    Double v = xmin + (xstep * i);
    yValues[i] = Double.parseDouble( solveArrayX( theEquation , v ) );
}

For example, the first time through the for loop, theEquation will have { "x", "^", "2" } . The next time will be { previousCalculatedAnswer, null, null }

Why is theEquation being changed? No other code is referencing it.

Why is theEquation being changed?

theEquation does not contain an array, it contains a reference to an array.

When you do solveArrayX( theEquation , v ) you're passing this reference to the solveArrayX method which changes the array. See lines 120 and 121 :

public String solveArrayX(String[] tA, double d){
    ...

        tA[i] = tA[i+2];
        tA[i+2] = "";
    ...
}

If you want to avoid this, you can use Arrays.copyOf(theEquation, theEquation.length) as argument to the method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM