2014-01-26 90 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