java equality_JAVA中equals()与==的区别详解

StackOverFlow中对equals()的使用提出了几个需要注意的地方:

equals will only compare what it is written to compare, no more, no less.

equals方法只会实现方法中所写的比较逻辑。

if a class does not override the equals method, then it defaults to the equals(Object o) method of the closest parent class that has overridden this method.

如果没有重写equals(),默认使用该类最近且重写了equals()的父类方法。需通过api查阅该父类equals()的实现逻辑,如果不符合你想要实现的,要重写equals()和hashCode()两个方法。

If no parent classes have provided an override, then it defaults to the method from the ultimate parent class, Object, and so you’re left with the Object#equals(Object o) method. Per the Object API this is the same as ==; that is, it returns true if and only if both variables refer to the same object, if their references are one and the same. Thus you will be testing for object equality and not functional equality.

如果没有父类重写equals(),则默认使用Objec类的equals()。通过API可知Object类的equals()实现逻辑与==一样。

Always remember to override hashCode if you override equals so as not to “break the contract”. As per the API, the result returned from the hashCode() method for two objects must be the same if their equals methods shows that they are equivalent. The converse is not necessarily true.

重写equals()的同时需重写hashCode(),查阅API可知,如果equals()返回true时,两个对象的hashCode也应该相等,否则不能保证结果完全正确。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值