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

查看:133
本文介绍了当我们有==运算符时为什么是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天全站免登陆