我是一个新的Java程序员,我试图实现一种方法来检查我的对象" feature vector"中两个"特征"阵列之间的平等性似乎真的很基本,但是该方法由于某种原因无法使用。它没有产生逻辑结果,我似乎找不到解决方案,请帮助
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) ;
}
初始代码中的错误将 result
初始化为 false
。这导致循环在第一次比较之前立即退出。
请注意,将布尔值与 true
和 false
进行比较,认为这是最不可能的练习。充其量是多余的。在最坏的情况下,您可能会创建一个难以发现的错误:
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;
}
您应该切换比较长度和比较各个特征的顺序:如果长度不同,则没有任何点进行比较!
您还应该在知道有区别的情况下立即返回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;
}
您的逻辑可能会出现一些问题。我会重写并在我继续时发表评论。
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;
}