1

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.

Dinal24
  • 3,162
  • 2
  • 18
  • 32
corey
  • 498
  • 3
  • 10

1 Answers1

0

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.

aioobe
  • 413,195
  • 112
  • 811
  • 826
  • thanks, i knew about arrays being pointers but i didnt know that it extends to functions that you pass the arrays! – corey Dec 22 '14 at 14:03
  • 3
    Just from curiosity: where exactly do you see lines 120, 121 in OP question? – Pshemo Dec 22 '14 at 14:03
  • 1
    Where did the OP post the link to `solveArrrayX` implementation? Can't find it in the question nor the history. – Predrag Maric Dec 22 '14 at 14:07
  • @PredragMaric, the OP posted it as a comment. The link is available in my answer. – aioobe Dec 22 '14 at 14:08
  • 2
    I would not have learned about referenced arrays by debugging. I am aware of debugging and have been at my debugger for half the day trying to fix this. Your comments arnt constructive at all. – corey Dec 22 '14 at 14:20
  • Well, you are coming off as a bit harsh. The behaviors of passing arrays is, to me, unintuitive. A debugger would not have helped me pass that mental block because I've been sitting here for hours at my debugger with no luck. – corey Dec 22 '14 at 15:44
  • Ah well, all that's left of @jalynn2 is his down vote now anyway. – aioobe Dec 22 '14 at 15:55