java - 具有相同哈希码但不相等的两个实例

标签 java equals hashcode

我正在阅读标题为- Java theory and practice: Hashing it out - Defining hashCode() and equals() effectively and correctly 的文章中引用的以下段落。

Defining equality The Object class has two methods for making inferences about an object's identity: equals() and hashCode(). In general, if you override one of these methods, you must override both, as there are important relationships between them that must be maintained. In particular, if two objects are equal according to the equals() method, they must have the same hashCode() value (although the reverse is not generally true).[emphasis added by me]

我的问题与该段的后半部分有关,“尽管通常情况并非如此”。一个类的两个不同实例如何可能具有相同的 hashCode 但不相等?

最佳答案

简单来说hashcode()就是一个通过某种公式生成hash的函数,所以会有一些冲突,两个不同的值可能会变成相同的hashcode。

如果我简单地通过将 mod 乘以 6 来计算哈希码,那么两个不同的值可能具有相同的哈希码。

关于java - 具有相同哈希码但不相等的两个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12707869/

相关文章:

java - 为每个不同的对象返回不同值的 hashCode() 方法是最有效的方法吗?

java - 使用 JNA 加载多个依赖库

java - 特性切换 Java 注解

java - SQLite - WHERE 子句中 IS 和 =(等于)的区别。 (使用 JDBC PreparedStatement)

java - 字符串比较是否相等

ruby - Ruby "foo".hash 的 Perl 等价物是什么?

java - 如何从StringArray中获取ItemArray?

Java 堆空间(java.lang.OutOfMemoryError)

MySQL:如果行相等则求和

Java:修改更改哈希码的id