0

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.

  • 2
    http://stackoverflow.com/questions/40480/is-java-pass-by-reference – epoch Apr 24 '14 at 14:06
  • Java is passing parameters by reference value, so you modify contents of `values` array when you pass its reference to the method – hoaz Apr 24 '14 at 14:09

4 Answers4

1

You are modifying the array in the second for

greywolf82
  • 21,813
  • 18
  • 54
  • 108
1

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:

Community
  • 1
  • 1
Heinzi
  • 167,459
  • 57
  • 363
  • 519
1

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.

Damien R.
  • 3,383
  • 1
  • 21
  • 32
1

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;
}
cyborg86pl
  • 2,597
  • 2
  • 26
  • 43