在Java中覆盖equals方法
考虑以下Java程序:
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 ");
}
}
}
Java
Complex c3 = c1; // (c3 == c1) will be true
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 ");
}
}
}
输出:
Not Equal
打印“Not Equal”的原因很简单:当我们比较 c1 和 c2 时,检查 c1 和 c2 是否引用同一个对象(对象变量在Java中总是引用)。 c1 和 c2 指的是两个不同的对象,因此值 (c1 == c2) 为 false。如果我们创建另一个引用说 c3 如下所示,那么 (c1 == c3) 将给出 true。
Java
Complex c3 = c1; // (c3 == c1) will be true
那么,我们如何检查对象内部的值是否相等呢? Java中的所有类都直接或间接地从 Object 类继承(参见第 1 点)。 Object 类有一些基本方法,如 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