等于方法不起作用

az_*_*993 0 java arrays equals object

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

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) ; 
}
Run Code Online (Sandbox Code Playgroud)

Ada*_*iss 6

初始代码中的错误是初始化resultfalse.这导致循环在第一次比较之前立即退出.

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

if (some_value = false) {  // DON'T do this -- it's always false!
Run Code Online (Sandbox Code Playgroud)

我之前已经建议,如果你绝对必须这样做,也许是由于未确诊的心理状况或技术负责人应该真正参与管理,使用尤达条件来保护自己:

if (false == some_value) {  // Syntax error, a single "=" will create.
Run Code Online (Sandbox Code Playgroud)

这是原始代码的更正和优化版本:

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;
}
Run Code Online (Sandbox Code Playgroud)