Java函数正在更新其输入变量

Sam*_*son 0 java eclipse java-6

我正在做一个实验室,从事健身功能.问题是我正在制作一个SmallChange()函数来执行它所说的内容,令人烦恼的是它似乎更新了你给它的变量,而它不应该.

这是完整课程的副本:https://gist.github.com/1710367

第38行是问题.

以下是功能.当我把它solution作为输入时solution,它会根据它做出的小改动进行更新,但我无法弄清楚如何或为什么.

谁知道我哪里出错了?它开始伤害我的大脑.

// Edits either the angle or velocity of our solution
// by a small amount (about 1% of the diffrence between max and min)
public static Double[] SmallChange(Double[] sol) {
    // Pick a 0 or 1
    switch (r.nextInt(2)) {
    case 1: // Changing the angle
        // The angle change amount
        Double angle = (angleLimits[1] - angleLimits[0]) * 0.01;

        // Make the change, either + or -
        if (r.nextInt(2) == 0) {
            sol[0] += angle;
        } else {
            sol[0] -= angle;
        }

        // Check it's within the limits
        if (sol[0] > angleLimits[1]) {
            sol[0] = angleLimits[1];
        } else if (sol[0] < angleLimits[0]) {
            sol[0] = angleLimits[1];
        }
        break;
    case 0: // Changing the velocity
        // The velocity change amount
        Double velocity = (velocityLimits[1] - velocityLimits[0]) * 0.01;

    // Make the change, either + or -
    if (r.nextInt(2) == 0) {
            sol[1] += velocity;
        } else {
            sol[1] -= velocity;
        }

    // Check it's within the limits
        if (sol[1] > velocityLimits[1]) {
            sol[1] = velocityLimits[1];
        } else if (sol[1] < velocityLimits[0]) {
            sol[1] = velocityLimits[1];
        }
        break;
    }

    return sol;
    }
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 8

在Java中,所有内容都按值传递 - 但该值始终是基元或引用.

所以任何数组变量的值都是对数组对象的引用.当您将该变量用作参数时,值(引用)最终将作为参数的初始值.它仍然引用与调用者变量相同的数组对象 - 因此调用者将看到对数组所做的任何更改.

所以只是为了澄清,你的陈述是不正确的:

令人讨厌的是它似乎更新了你给它的变量,当它不应该

它根本没有改变变量的值:调用代码中的变量仍具有与之前相同的值,即对同一数组的引用.只是该方法正在改变数组的内容.

这就像在一张纸上复制你的地址,然后把它交给某人:他们不能改变你居住的地方,但他们可以改变你的前门的颜色.


现在,解决你的问题......

如果要克隆数组,则必须明确地执行此操作.例如:

public static Double[] smallChange(Double[] sol) {
    Double[] ret = (Double[]) sol.clone();
    // Now work on ret instead of sol, and return ret at the end
Run Code Online (Sandbox Code Playgroud)

可以重新分配sol,但我个人不会.

请注意,您可能还想使用double[]而不是Double[].