[英]Equals method not working
我是一名新的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) ;
}
初始代碼中的錯誤將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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.