简体   繁体   English

方法意外更改我的数组的值

[英]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? 如果在调用此方法之前记录array的值,我得到1.0,1.0,但是在调用该方法后,我得到90.0,90.0,为什么? If I don't change values[] . 如果我不更改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) 我知道这种方法正在这里发生,因为当我删除它时,我得到1.0,1.0(我实际上想要得到的)

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. 感谢您提供答案,以便我正确理解:如果更改了方法的参数,则在调用方法时设置为参数的对象也会更改。

您正在第二个中修改数组

Array variables are just references. 数组变量只是引用。 If you pass values as data , data points to the same array as values . 如果将values作为data传递,则data指向与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 : 如果您不想这样做,则需要进行复制

You are modifying your array here: data[i] = 180 * (data[i] / total); 您正在此处修改数组: 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. 您可以在函数的参数中获取数组的地址,而不是其副本,因此,如果在函数中对其进行修改,它将在壁挂calculateData函数时修改您传递的数组。

You need a new array inside your method like newData in the code below, which you need to return from a method: 您需要在方法内部添加一个新数组,如下面的代码中的newData ,您需要从方法中return该数组:

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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