默认的.equals和.hashCode如何适用于我的课程? [英] How default .equals and .hashCode will work for my classes?

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

问题描述

说我有自己的班级

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

它有一些属性和方法。它没有实现equals,也没有实现hashCode。

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

一旦我们调用equals和hashCode,默认的实现是什么?来自Object类?他们是什么?默认等于如何工作?默认的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的值为true)时,此方法才返回

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天全站免登陆