什么是Java中的哈希码? [英] What is hashcode in Java?

查看:125
本文介绍了什么是Java中的哈希码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读了几篇文章和官方文档之后,我无法获得在Java中使用哈希码的实际目的。



有人提到它是使用 equals()方法进行对象比较的合约。两个相同的对象必须具有相同的哈希码,但是两个不相等的对象在每个对象中不一定具有不同的哈希码。这真的令人困惑。



你能用简单的语言解释Java中哈希码的用途吗? 如果Java没有哈希码,它真正有什么不同?

After reading several articles and official documents, I could not get the actual purpose of having hashcode in Java.

Somewhere it was mentioned that it is a contract for object comparison using the equals() method. Two objects which are same must have the same hashcode but two unequal objects don''t necessarily have different hashcode in each. It''s really confusing.

Could you please explain in plain language the purpose of hashcode in Java? What does it really make a difference, if Java doesn''t have hashcode?

推荐答案

哈希代码不在Java中。这是在计算中无处不在的重要算法:

http://en.wikipedia.org/wiki/Hash_function [ ^ ]。



在Java中,它很重要,因为您的类可以基于使用哈希码的算法在某些集合中使用。只有在定义自己的相等方法时提供此函数的某些实现,您的元素才能在此类算法中正确运行。逻辑上相等的对象应该表现出相同的哈希码值,不等的对象应该返回哈希码的值,这些值的概率很高 - 这是类实现的主要要求。



对不起,我不想再解释一下。请参阅我曾经为.NET提供的解释:

C#.Net 中的Object.GetHashCode()方法[ ^ ]。



在Java中,一切都是一样的,只有它有不同但相似的集合类型。< br $>






你可能会感到困惑,知道如何为你的课程实现哈希码这是必需的。我会给你一个非常简单的食谱。考虑您的类有几个字段,用于等于实现。假设他们已经有哈希代码的实现,取所有哈希代码值并对它们进行二进制异或。将结果值作为组合对象的哈希码返回。就是这样。



对于家庭练习,请考虑为什么这个实现有效。 :-)



-SA
Hash code is not in Java. This is important algorithm use everywhere in computing:
http://en.wikipedia.org/wiki/Hash_function[^].

In Java, it is important because your class can be uses in some collection based on the algorithms using hash code. Your elements will behave correctly in such algorithms only if you provide some implementation of this function as soon as you define your own equality method. Logically equal objects should manifest equal hash code values, and unequal objects should return values of the hash code which are different with high probability — this is the major requirement for the class implementation.

Sorry, I don''t want to explain it once again. Please see my explanation I once provided for .NET:
Object.GetHashCode() Method in C#.Net[^].

In Java, everything is the same, only it has different but similar collection types.



You might be puzzled to know how should you implement hash code for your classes when it is required. I''ll give you a very simple recipe. Consider your class has several fields which are use in equals implementation. Supposing they already have implementation of hash code, take all their hash code values and make a binary XOR of all of them. Return the resulting value as a hash code of the composing object. That''s it.

For a home exercise, think why this implementation works. :-)

—SA


这篇关于什么是Java中的哈希码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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