我是一个新的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) ;
}发布于 2014-01-27 06:31:51
你应该改变比较长度和比较单个特征的顺序:如果长度不同,就没有必要比较其余的!
一旦你知道有差异,你也应该返回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;
}https://stackoverflow.com/questions/21370075
复制相似问题