2014-01-26 124 views
0

我是一個新的Java程序員,即時通訊試圖實現一個方法來檢查之間我的對象「FeatureVector」 似乎很基本的,但該方法不工作的一些原因,內部的兩個「特色」陣列的平等;它不產生合乎邏輯的結果,我似乎無法找到一個解決方案,請大家幫忙equals方法不工作

public boolean equals (FeatureVector x) 
{ 
    boolean result =false ; 
    boolean size = false ; 
    for (int i =0 ; (i < this.features.length && result == true);i ++ ) 
    { 
     if (this.features[i] == x.features[i]) {result = true ;} 
     else {result = false ; } 
    } 

    if (this.features.length == x.features.length) {size = true ;} 
    else {size =false; } 
    return (result && size) ; 
} 
+2

features數組中包含了什麼?字符串?整型? –

+0

你是什麼意思「它不會產生合乎邏輯的結果」?你能給個例子嗎?我的猜測是你需要用自己的'.equals'方法來測試數組項的相等性,而不是'=='。 – Teepeemm

回答

1

您應該切換比較長,比較各個特徵的順序:如果長度是不同的,有沒有比較點其餘的部分!

只要您知道存在差異,您也應該返回false - 再次,繼續循環的唯一原因是如果您認爲可能會返回true

這裏是你如何改變你的計劃:

public boolean equals (FeatureVector x) 
{ 
    if (this.features.length != x.features.length) { 
     return false; 
    } 
    // If we get here, the sizes are the same: 
    for (int i = 0 ; i < this.features.length ; i++) 
    { 
     if (this.features[i] != x.features[i]) { 
      return false; 
     } 
    } 
    // If we got here, the sizes are the same, and all elements are also the same: 
    return true; 
} 
6

在最初的代碼中的bug已被初始化resultfalse。這導致循環在第一次比較之前立即退出。

請注意,將布爾值與truefalse進行比較時,將其視爲比最佳做法要差。充其量,這是多餘的。在最壞的情況,你可能會創建一個很難發現錯誤:

if (some_value = false) { // DON'T do this -- it's always false! 

我之前所說,如果你絕對必須這,或許是由於確診的心理條件或技術主管誰應該真的已經在管理,使用尤達條件保護自己:

if (false == some_value) { // Syntax error, a single "=" will create. 

這裏有一個修正和優化原代碼的版本:

public boolean equals (FeatureVector x) { 

    // Do the "cheapest" test first, so you have an opportunity to return 
    // without waiting for the loop to run. 
    if (this.features.length != x.features.length) { 
    return false; 
    } 

    // There's no need to "accumulate" the results of each comparison 
    // because you can return immediately when a mismatch is detected. 
    for (int i = 0; i < this.features.length; i++) { 
    if (this.features[i] != x.features[i]) { 
     return false; 
    } 
    } 
    return true; 
} 
-1

有幾件事情可能會出現您的邏輯錯誤。我會一邊重寫一邊評論。

public boolean equals (FeatureVector x) 
{ 

    /* 
    * Check for the length first, if the lengths don't match then 
    * you don't have to bother checking each elements. Saves time! 
    */ 
    if (this.features.length != x.features.length) return false; 

    for (int i =0 ; i < this.features.length; i++) { 
     /* 
     * As soon as you find a mismatching element, return out of the 
     * loop and method, no need to keep checking. Saves time! 
     */ 
     if (this.features[i] != x.features[i]) return false; 
    } 

    // If the logic makes it this far, then all elements are equal 
    return true; 
} 
+0

Aww,downvote沒有解釋? – lebolo