默认的 .equals 和 .hashCode 如何为我的类工作? [英] How default .equals and .hashCode will work for my classes?

查看:36
本文介绍了默认的 .equals 和 .hashCode 如何为我的类工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有自己的班级

public class MyObj { /* ... */ }

它有一些属性和方法.它不实现equals,不实现hashCode.

It has some attributes and methods. It DOES NOT implement equals, DOES NOT implement hashCode.

一旦我们调用了equals和hashCode,默认的实现是什么?从对象类?他们是什么?默认的 equals 将如何工作?默认的 hashCode 将如何工作以及将返回什么?== 只会检查它们是否引用了同一个对象,所以很简单,但是 equals() 和 hashCode() 方法呢?

Once we call equals and hashCode, what are the default implementations? From Object class? And what are they? How the default equals will work? How the default hashCode will work and what will return? == will just check if they reference to the same object, so it's easy, but what about equals() and hashCode() methods?

推荐答案

是的,默认实现是 Object 的(一般来说;如果您从重新定义 equals 和/或 hashCode 的类继承,那么您将改用该实现).

Yes, the default implementation is Object's (generally speaking; if you inherit from a class that redefined equals and/or hashCode, then you'll use that implementation instead).

来自文档:

<代码>等于

Object 类的 equals 方法实现了对象上最具辨别力的可能等价关系;也就是说,对于任何非空引用值 x 和 y,此方法返回当且仅当 x 和 y 指代同一个对象时才为真(x == y 的值为真).

The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).

hashCode

在合理可行的情况下,类 Object 定义的 hashCode 方法确实为不同的对象返回不同的整数.(这通常通过将对象的内部地址转换为整数来实现,但 JavaTM 编程语言不需要这种实现技术.)

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)

这篇关于默认的 .equals 和 .hashCode 如何为我的类工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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