2012-01-31 19 views
0

我正在做一个实验,目前正在研究健身功能。问题是我正在做一个SmallChange()函数来执行它的操作,令人讨厌的是它似乎更新了你给它的变量,但它不应该这么做。Java函数正在更新其输入变量

这里是满级的副本: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; 
    } 
+0

你想调用你的方法'smallChange',而不是'SmallChange'。 – 2012-01-31 13:09:08

+0

这是因为方法名称通常以SmallCase开头(噢,我做了一个双关!) – 2012-01-31 13:36:00

回答

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 

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

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

+0

啊,不是我想象的,但现在我明白了。谢谢! – 2012-01-31 13:36:41