java equals覆盖,为什么我们必须覆盖Java中的equals()方法?

I have some confusion about the reason that we override the .equals method.

For example:

Test test1 = new Test(3);

Test test2 = new Test(3);

//The if comparison does the same thing that the overridden `.equals()` method does.

if(test1.equals(test2)){

System.out.println("test1 and test2 are true in .equals()");

}

// Override .equals method.

public boolean equals(Object object) {

if(object instanceof Test && ((Test)object).getValue() == this.t) {

return true;

} else {

return false;

}

}

I do not understand why we have to override the .equals() method.

解决方案

Default implementation of equals() class provided by java.lang.Object compares memory location and only return true if two reference variable are pointing to same memory location i.e. essentially they are same object.

Java recommends to override equals and hashCode method if equality is going to be defined by logical way or via some business logic: example:

many classes in Java standard library does override it e.g. String overrides equals, whose implementation of equals() method return true if content of two String objects are exactly same

Integer wrapper class overrides equals to perform numerical comparison etc.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值