user3552603
user3552603

Reputation:

Method is changing values of my array unexpectedly

Method calculating percentages (from array which I don't want to be changed but it is):

private float values[] = { AGREE, DISAGREE };

private float[] calculateData(float[] data) {
    // TODO Auto-generated method stub
    float total = 0;
    for (int i = 0; i < data.length; i++) {
        total += data[i];
    }
    // 180 is the amount of degrees of the circle - setting it up to half
    // circle 360 means full circle
    for (int i = 0; i < data.length; i++) {
        data[i] = 180 * (data[i] / total);
    }

Calling the method:

float[] degrees = calculateData(values);

If I log the values of array before this method was called I get 1.0,1.0 but after method was called I get 90.0,90.0 why? If I don't change values[].

I know that it is happening here in that method because when I remove it I get 1.0,1.0 (what I actually want to get)

EDIT:

Thank you for the answers so if I understand it correctly: if parameter of the method is changed also the object set to be parameter, when method was called, becomes changed.

Upvotes: 0

Views: 69

Answers (4)

cyborg86pl
cyborg86pl

Reputation: 2617

You need a new array inside your method like newData in the code below, which you need to return from a method:

private float[] calculateData(float[] data) {

    float[] newData;

    float total = 0;
    for (int i = 0; i < data.length; i++) {
        total += data[i];
    }
    for (int i = 0; i < data.length; i++) {
        newData[i] = 180 * (data[i] / total);
    }

    return newData;
}

Upvotes: 1

Damien R.
Damien R.

Reputation: 3373

You are modifying your array here: data[i] = 180 * (data[i] / total);

You get the address of the array in the parameter of your function, not a copy of it, so if you modify it in your function, it will modify the array you passed when walling your calculateData function.

Upvotes: 1

Heinzi
Heinzi

Reputation: 172220

Array variables are just references. If you pass values as data, data points to the same array as values. Consider the following example:

int[] a = new int[] {1, 2, 3};
int[] b = a;
b[0] = 4;

// a is now {4, 2, 3}

If you don't want this, you need to make a copy:

Upvotes: 1

greywolf82
greywolf82

Reputation: 22173

You are modifying the array in the second for

Upvotes: 1

Related Questions