2012-01-31 28 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