为什么当我们有 == 运算符时使用 equals() 方法? [英] why equals() method when we have == operator?

查看:27
本文介绍了为什么当我们有 == 运算符时使用 equals() 方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我看到 equals() 方法的实现时,它所做的只是与 == 所做的相同.所以我的问题是,当我们有 == 运算符时,需要将它作为单独的方法吗?

When i see the implementation of equals() method it does nothing but same as what == does. So my question is what was the need to have this as separate method when we have == operator which does the same work?

推荐答案

你不能重载 == 操作符,但是你可以重载 equals(Object) 如果你希望它的行为与 == 运算符不同,即不比较引用而是实际比较对象(例如使用它们的全部或部分字段).

You can not overload the == operator, but you can override equals(Object) if you want it to behave differently from the == operator, i.e. not compare references but actually compare the objects (e.g. using all or some of their fields).

此外,如果您确实覆盖了 equals(Object),也请查看 hashCode().这两个方法需要兼容(即根据equals(Object)相等的两个对象需要有相同的hashCode()),否则各种奇怪的错误将发生(例如,将对象添加到集合或地图时).

Also, if you do override equals(Object), have a look at hashCode() as well. These two methods need to be compatible (i.e. two objects which are equal according to equals(Object) need to have the same hashCode()), otherwise all kinds of strange errors will occur (e.g. when adding the objects to a set or map).

这篇关于为什么当我们有 == 运算符时使用 equals() 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆