Java中的equals()和hashCode()契约 [英] equals() and hashCode() contract in Java

查看:181
本文介绍了Java中的equals()和hashCode()契约的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Bert Bates和Kathy Sierra的SCJP 6学习指南在第554页(以及其他要求中)指出 x.hashCode()!= y.hashCode()要求x.equals(y)== false

The SCJP 6 Study Guide from Bert Bates and Kathy Sierra states on page 554 (among other requirements) that x.hashCode() != y.hashCode() requires that x.equals(y) == false.

但是Javadoc for Object没有明确提到这样的要求。引用:

如果两个对象根据equals(Object)方法相等,那么在两个对象中的每一个上调用hashCode方法必须产生相同的整数结果。

But the Javadoc for Object doesn't mention such requirement explicitly. Quote:
If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

我应该采用Javadoc所说的物质含义,例如 eq - > hc ?然后这两个来源之间不会发生冲突。

Should I take what Javadoc says as a material implication, such as eq -> hc? Then there would be no conflict between these two sources.

推荐答案

正如z5h所说,这些陈述是等价的。

As z5h says, the statements are equivalent.

对于逻辑条件x和y,x暗示y与!y暗示!x相同。

For logical conditions x and y, "x implies y" is the same as "!y implies !x".

如果有东西是公共汽车,它的红色在逻辑上等同于如果某些东西不是红色,那它不是公共汽车。

"If something is a bus, it's red" is logically equivalent to "if something isn't red, it's not a bus."

这是对位


我应该采取Javadoc所说的物质含义,例如eq - > hc。

Should I take what Javadoc says as a material implication, such as eq -> hc.

是的,这正是它所说的:两个物体相等在等于下暗示他们的哈希码必须相等。

Yes, that's exactly what it's saying: two objects being equal under equals implies their hashcodes must be equal.

这篇关于Java中的equals()和hashCode()契约的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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