Java 面向对象/Java 多态
在Java中重写equals方法
考虑下面的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是否指向同一个对象。c1和c2引用两个不同的对象,因此值(c1 == c2)为false。如果我们创建另一个引用,比如说c3,那么(c1 == c3)将赋予true。
Complex c3 = c1; // (c3 == c1) will be true
那么,我们如何检查对象内部的值是否相等?Java中的所有类从对象类继承,直接或间接地。该Object类有类似克隆的一些基本方法()的toString(),equals()方法,...等。
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()。