我们应该总是重写等号吗? [英] Should we always override equals?

查看:129
本文介绍了我们应该总是重写等号吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当编写自己的类时,是否总是需要重写 equals(Object o)

When writing one's own classes, is it always necessary to override equals(Object o)?

我不会,它会自动检查所有的字段是否相同?或者,它只是检查两个变量是否指向同一个对象?

If I don't, will it automatically check that all the fields are the same? Or does it just check if the two variables point to the same object?

推荐答案

如果一个正在写一个类,以某种方式比较其对象,则应重写 equals hashCode 方法。

If one is writing a class that is going to have its objects be compared in some way, then one should override the equals and hashCode methods.

不提供显式的 equals 方法将导致继承 equals 方法的行为超类,在超类是 Object 类的情况下,那么它将是Java API规范中 Object 类。

Not providing an explicit equals method will result in inheriting the behavior of the equals method from the superclass, and in the case of the superclass being the Object class, then it will be the behavior setforth in the Java API Specification for the Object class.

提供 equals 方法的一般合同可以在 对象 类,特别是 equals hashCode 方法。

The general contract for providing an equals method can be found in the documentation for the Object class, specifically, the documentation of the equals and hashCode methods.

这篇关于我们应该总是重写等号吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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