[英]Why does my custom equals method (doubles and integers) not work?
我有一個自定義的equals來檢查名為Pair的對象的相等性。
class Pair implements Comparable <Parr> {
double coef;
int power;
Pair(double a, int b) {
coef = a;
power = b;
}
我的自定義equals方法是(位於類對中):
@Override
public boolean equals(Object o) {
if (!(o instanceof Pair))
return false;
Pair that = (Pair) o;
return that.coef == this.coef && that.power == this.power;
}
我已經檢查了對象的打印是否相同,並且它們確實相同。
1.0 1 2.0 0
1.0 1 2.0 0
我從另一個名為Test的文件中調用自定義等於。
class Test {
public static void main(String[] args) {
orig = pol1.differentiate().integrate();
System.out.print(orig);
if (orig.equals(pol1))
System.out.println(" (is equal.)");
else
System.out.println(" (is not equal.)");
還有我的類Polynomial,它是一個內部有Pair對象的數組列表。
class Polynominal implements PolynominalInterface {
ArrayList<Pair> terms = new ArrayList<Pair>();
我在互聯網上看了一下,發現無法在Equals方法中使用==,但是我正在使用Intergers和Doubles,因此equals()無法正常工作。
誰能指出我正確的方向?
如果orig
和pol1
是Polynomial
實例,則此
if (orig.equals(pol1))
僅當您同時實現Polynomial#equals()
時才有效; 這將迭代兩個ArrayList
,並確保各個Pair
相等(當然使用Pair#equals()
)。
好的,感謝Ravi Thapliyal,我找到了解決方案。
在我的Polynominal類中添加自定義equals方法后,此問題已解決。
@Override
public boolean equals(Object o) {
if (!(o instanceof Polynomial))
return false;
Polynomial that = (Polynomial) o;
return that.terms.equals(terms);
}
使用Double.compare(double,double)方法代替==。
在Java中,浮點比較是“模糊的”。
您將需要實現類似於以下內容的Polynomail.equals()方法:
public boolean equals(Object o) {
if (!(o instanceof Polynomial)) return false;
Polynomial other = (Polynomial) o;
if (this.terms==null && other.terms==null) return true;
// A suitable equals() method already exists for ArrayList, so we can use that
// this will in turn use Pair.equals() which looks OK to me
if (this.terms!=null && other.terms!=null) return this.terms.equals(other.terms);
return false;
}
我想到兩個問題:第一個問題是,對於任何兩個不同的對象實例,無論其內容如何,默認的hashCode()
方法都很少返回相同的值。 如果equals()
方法從不將兩個不同的對象實例報告為相等,那么這是一件好事,但如果這樣做,則是一件壞事。 覆蓋Object.equals()
每個對象也應該覆蓋Object.hashCode()
這樣,如果x.equals(y)
,則x.hashCode()==y.hashCode()
; 這很重要,因為即使是非哈希通用集合也可能使用對象的哈希碼來加快比較。 如果您不想編寫“真正的”哈希函數,只需選擇一些任意整數,然后讓您類型的hashCode()
方法始終返回該整數即可 。 任何將您的類型存儲到其中的哈希集合都將運行緩慢,但是所有將其存儲在其中的集合都應正確運行。
您可能會看到的第二個問題是,浮點比較有時是不可靠的。 兩個數字可能基本相等,但比較不相等。 更糟糕的是,IEEE出於任何原因決定,浮點“非數字”值應比較不等於所有值, 包括它們自己 。
同時考慮這兩個問題,我建議您可能希望重寫equals
方法以鏈接到double
的equals
方法。 此外,如果在它的存儲在集合中的對象既不場將被修改,有你hashCode()
方法計算hashCode
的的int
,通過一些大奇數相乘,然后用添加或異說hashCode
的double
。 如果將對象存儲在集合中時可能對其進行了修改,則讓hashCode()
返回一個常量。 如果不重寫hashCode()
,則不能期望包含您的對象的任何對象的equals
方法都能正常工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.