java中重写equals方法_在Java中重写equals方法 - Break易站

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()。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值