为什么 hashCode() 可以为 Java 中的不同对象返回相同的值? [英] Why can hashCode() return the same value for different objects in Java?

查看:32
本文介绍了为什么 hashCode() 可以为 Java 中的不同对象返回相同的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

引自我正在阅读的书 Head第一个Java:

A quote from the book I'm reading Head First Java:

重点是哈希码可以相同,但不一定保证对象相等,因为 hashCode() 方法中使用的哈希算法"可能恰好为多个返回相同的值对象.

The point is that hashcodes can be the same without necessarily guaranteeing that the objects are equal, because the "hashing algorithm" used in the hashCode() method might happen to return the same value for multiple objects.

为什么 hashCode() 方法可能会为不同的对象返回相同的值?这不会引起问题吗?

Why might the hashCode() method return the same value for different objects? Does that not cause problems?

推荐答案

散列 一个对象意味着找到一个很好的、描述性的值(数字),可以被同一个实例复制一次又一次地".因为来自 Java 的 Object.hashCode() 的哈希码属于 int 类型,所以您只能有 2^32 不同的值.这就是为什么当两个不同的对象产生相同的 hashCode 时,您会根据散列算法产生所谓的冲突".

hashing an object means "finding a good, descriptive value (number) that can be reproduced by the very same instance again and again". Because hash codes from Java's Object.hashCode() are of type int, you can only have 2^32 different values. That's why you will have so-called "collisions" depending on the hashing algorithm, when two distinct Objects produce the same hashCode.

通常,这不会产生任何问题,因为 hashCode() 主要与 equals() 一起使用.例如,HashMap 将对其键调用 hashCode(),以了解这些键是否已包含在 HashMap 中.如果 HashMap 没有找到哈希码,很明显 HashMap 中还没有包含该键.但如果是这样,它将必须使用 equals() 仔细检查所有具有相同哈希码的键.

Typically, this does not produce any problems, because hashCode() is mostly used together with equals(). For instance, a HashMap will call hashCode() upon its keys, to know whether the keys may already be contained in the HashMap. If the HashMap does not find the hash code, it's obvious the key is not contained in the HashMap yet. But if it does, it will have to double-check all keys having that same hash code using equals().

A.hashCode() == B.hashCode() // does not necessarily mean
A.equals(B)

但是

A.equals(B) // means
A.hashCode() == B.hashCode()

如果 equals()hashCode() 实现正确.

If equals() and hashCode() are implemented correctly.

有关一般 hashCode 合约的更准确描述,请参阅 Javadoc.

For a more precise description of the general hashCode contract, see the Javadoc.

这篇关于为什么 hashCode() 可以为 Java 中的不同对象返回相同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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