为什么在Object中定义了equals和hashCode? [英] Why equals and hashCode were defined in Object?

查看:147
本文介绍了为什么在Object中定义了equals和hashCode?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

决定在java.lang.Object中包含这些方法的原因是什么?对于许多类来说,平等和散列是没有意义的。

What's the reasoning behind decision to include these methods in the java.lang.Object? Equality and hashing doesn't make sense for many classes.

制作两个接口更合乎逻辑:

It would be more logical to make two interfaces:

interface Equalable {
    boolean equals(Equalable other);
}

interface Hashable extends Equalable {
    int hashCode();
}

例如HashSet定义可能看起来像

For example HashSet definition might look like

class HashSet<T extends Hashable> ...

这会阻止一个常见的初学者错误 - 使用一组项目而不实现equals / hashCode。

It would prevent one of the common beginner mistakes - using set of items without implementing equals/hashCode.

推荐答案

当我们实现接口时,我们注入(或接受)接口定义的合约。

When we implement an Interface we inject (or accept) the contract defined by the interface.

Equalable &安培; Hashable 是两个不同的合约。但是如果我们仔细观察一下,我们会看到它们彼此依赖,这意味着它们是单一界面的一部分,类似于 EqualableAndHashable

Equalable & Hashable are two different contracts. But if we take a look closely then we will see that both of them depend on each other, which means they are part of a single interface, something like EqualableAndHashable.

现在显而易见的问题是,它们是否应该成为新的 EqualableAndHashable interface或 Object

Now the obvious question is, whether they should be part of this new EqualableAndHashable interface or Object?

让我们看看。我们有 ==(等于运算符)来检查两个对象的相等性。 == 运算符确认两个不同的基元/对象的值/引用是否相等。但这并不总是可以通过检查 == 运算符来回答。

Let's find out. We have == (equal operator) to check equality of two objects. == operator confirms whether values/references are equal for two different primitives/objects. But this is not always possible to answer just by checking with the == operator.

现在的问题是,是否这个等式也是契约,应该通过接口或部分Object类注入?

Now question is, whether this equality, which is also a contract, should be injected via interfaces or part of the Object class?

如果我们来看看,我们不能只说出这样的话:

If we take a look, we can't just say something like:


TypeX 不保证平等合同。

如果某些对象类型提供相等性而某些对象类型不提供,则会变得混乱。这意味着 TypeX 的对象必须遵守对所有其他对象类型都为true的相等协定。因此,它不能从接口注入相等性,因为默认情况下,相等应该是任何对象的合同的一部分,否则会产生混乱。

It will become a chaos if some object types offer equality and some do not. Which means object of TypeX must honor the equality contract which is true for all other object types as well. So, it must not inject equality from a interface, because equality should be the part of the contract for any object by default, otherwise it will create chaos.

所以我们需要提出实现的对象等于。但它不能只实现 equals 方法,它还需要实现 hashcode 方法。

So we need Objects to come up with implementation of equals. But it can't implement only the equals method, it also needs to implement the hashcode method.

这篇关于为什么在Object中定义了equals和hashCode?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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