0

I created a method that puts the read numbers into a NumberArray and in total 2 NumberArrays are created per input file. I have created an array of the object NumberRow on the line I marked with "!!!!". I put the read double into the array. However, when I read those arrays, numberRow[0] is not correct; all the values belonging in numberRow[1] are in there, and the values in numberRow[1] are correct. There is probably a simple solution, but I really don't see what is going wrong here.

Unit[] unitArray = new Unit[dataset.numberOfRecords];
    double[] emptyDoubleArray = new double[dataset.numberOfRecords];
    for(int x = 0; x<dataset.numberOfVariables; x++){
        numberRow[x] = new NumberRow(emptyDoubleArray);
    }
    for(int i = 0; i<dataset.numberOfRecords; i++){
        String label = in.next();
        double[] elementsPerUnit = new double[dataset.numberOfVariables];
        for(int k = 0; k<dataset.numberOfVariables; k++){
            double misc = in.nextDouble();
        !!!!!   numberRow[k].NumberArray[i] = misc;
            elementsPerUnit[k] = misc;
        }
        unit = new Unit(label, elementsPerUnit);
        unitArray[i] = unit;
    }
    unitRow = new UnitRow(unitArray);
    out.print(Arrays.toString(numberRow[0].NumberArray));
}
1
  • The above code is virtually impossible to follow. You've left out far too much context (and also left out all the comments). Commented Jun 5, 2013 at 1:31

1 Answer 1

1

Arrays are objects in Java. That is, they are not copied and passed by value (like int, etc), they are passed by reference (like Object, String...)

If you create an array with new and pass it to two objects, there is still only one array (you only used new once, think about it this way). When one object edits the array, the single copy of the array, having been edited, 's edits are seen by the other object.

The solution is, create a new array if it should be distinct from all other arrays.

EDIT: You create one array here (note the new)

double[] emptyDoubleArray = new double[dataset.numberOfRecords];

this one array is passed to all NumberRows (note, no new)

numberRow[x] = new NumberRow(emptyDoubleArray);

therefore if I edit any NumberRow's array it is seen in all NumberRows.

Sign up to request clarification or add additional context in comments.

3 Comments

But am I not doing this here? for(int x = 0; x<dataset.numberOfVariables; x++){ numberRow[x] = new NumberRow(emptyDoubleArray); }
That isn't creating an array, it's creating a NumberRow object.
Oh wait, I see, thank you very much ! I put the empty double array in the for loop, creating two seperate ones.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.