本文介绍了为什么 Java 不允许在 Enum 中覆盖 equals(Object)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到以下代码段...

I've noticed that the following snippet...

@Override
public boolean equals(Object otherObject) {
    ...
}

... 不允许用于枚举,因为方法 equals(Object x) 在 .为什么会这样?

...is not allowed for an Enum, since the method equals(Object x) is defined as final in Enum. Why is this so?

我想不出任何需要为 Enum 覆盖 equals(Object) 的用例.我只是想知道这种行为背后的原因.

I cannot think of any use case which would require overriding equals(Object) for Enum. I'm just curious to know the reasoning behind this behavior.

推荐答案

除了 return this == other 之外的任何事情都会违反直觉并违反 最小惊讶原则.当且仅当它们是同一个对象并且覆盖此行为的能力容易出错时,两个枚举常量应该equal.

Anything but return this == other would be counter intuitive and violate the principle of least astonishment. Two enum constants are expected to be equal if and only if they are the same object and the ability to override this behavior would be error prone.

同样的推理适用于 hashCode()clone()compareTo(Object)name()ordinal()getDeclaringClass().

Same reasoning applies to hashCode(), clone(), compareTo(Object), name(), ordinal(), and getDeclaringClass().

JLS 并没有促使选择使其成为最终版本,而是在枚举上下文中提到 equals 这里.片段:

The JLS does not motivate the choice of making it final, but mentions equals in the context of enums here. Snippet:

Enum 中的 equals 方法是一个最终方法,它仅调用其参数上的 super.equals 并返回结果,从而执行身份比较.

这篇关于为什么 Java 不允许在 Enum 中覆盖 equals(Object)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 10:33