Java中重写equals方法

考虑下面的java程序:

null

JAVA

class Complex {
private double re, im;
public Complex( double re, double im) {
this .re = re;
this .im = im;
}
}
// Driver class to test the Complex class
public class Main {
public static void main(String[] args) {
Complex c1 = new Complex( 10 , 15 );
Complex c2 = new Complex( 10 , 15 );
if (c1 == c2) {
System.out.println( "Equal " );
} else {
System.out.println( "Not Equal " );
}
}
}


输出:

Not Equal 

打印“不相等”的原因很简单:当我们比较c1和c2时,会检查c1和c2是否都指向同一个对象( 在Java中,对象变量总是引用 ).c1和c2指的是两个不同的对象,因此值(c1==c2)为假。如果我们创建另一个引用,比如下面的c3,那么(c1==c3)将给出true。

JAVA

Complex c3 = c1; // (c3 == c1) will be true


那么,我们如何检查对象内部的值是否相等?Java中的所有类都直接或间接地继承自对象类(参见本文第1点) ).这个 对象类 有一些基本方法,如clone()、toString()、equals()、等,。。我们可以重写类中的equals方法来检查两个对象是否有相同的数据。

JAVA

class Complex {
private double re, im;
public Complex( double re, double im) {
this .re = re;
this .im = im;
}
// Overriding equals() to compare two Complex objects
@Override
public boolean equals(Object o) {
// If the object is compared with itself then return true
if (o == this ) {
return true ;
}
/* Check if o is an instance of Complex or not
"null instanceof [type]" also returns false */
if (!(o instanceof Complex)) {
return false ;
}
// typecast o to Complex so that we can compare data members
Complex c = (Complex) o;
// Compare the data members and return accordingly
return Double.compare(re, c.re) == 0
&& Double.compare(im, c.im) == 0 ;
}
}
// Driver class to test the Complex class
public class Main {
public static void main(String[] args) {
Complex c1 = new Complex( 10 , 15 );
Complex c2 = new Complex( 10 , 15 );
if (c1.equals(c2)) {
System.out.println( "Equal " );
} else {
System.out.println( "Not Equal " );
}
}
}


输出:

Equal 

另外,当我们重写equals()时,建议也重写hashCode()方法。如果我们不这样做,相等的对象可能会得到不同的散列值;基于散列的集合,包括HashMap、HashSet和Hashtable不能正常工作(请参见 更多细节)。我们将在另一篇文章中详细介绍hashCode()。 参考资料: 有效Java第二版 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞10 分享