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

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

问题描述

我正在阅读的书中引用了头一个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().

Ie

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

但是

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

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

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

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

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

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