等于方法不起作用

时间:2014-01-26 22:23:04

标签: java arrays object equals

我是一名新的Java程序员,我试图实现一个方法来检查我的对象“FeatureVector”中两个“features”数组之间的相等性 看起来很基本,但这种方法由于某种原因不起作用;它不会产生逻辑结果,我似乎无法找到解决方案,请帮助

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) ; 
}

3 个答案:

答案 0 :(得分:6)

初始代码中的错误是将result初始化为false。这导致循环在第一次比较之前立即退出。

请注意,将布尔值与truefalse进行比较时,这被认为是一种不太好的做法。充其量,它是多余的。在最坏的情况下,您可能会创建一个难以发现的错误:

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

我之前已经建议,如果你绝对必须这样做,可能是由于未确诊的心理状况或应该真正管理过的技术主管,使用Yoda条件来保护自己:

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 :(得分: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; 
}

答案 2 :(得分:-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;
}