为什么具有相同哈希码的两个对象不一定相等? [英] Why two objects with the same hashcode are not necessarily equals?

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

问题描述

当前,我很有趣地钻研了JSE源代码.从一些教程中,我发现了一个原理两个equals对象(即,对象a和b a.equals(b)返回true)必须具有相同的哈希码,另一方面,两个具有相同哈希码的对象并不一定等于.根据Java API的HashTable源代码(

Currently I drilled into the JSE source code for fun. From some tutorials I found a principle two equals objects (i.e. as to object a and b a.equals(b) returns true) must have the same hashcode, on the other hand, two objects with the same hashcode are not necessarily equals. According to the HashTable source code of Java API (http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/Hashtable.java), e.g. refer to line 254, we can almost derive equals => same hashcode, but I still can not fully understand why two objects with the same hashcode are not necessarily equals. Anyone can give more reasoning on this? Thanks in advance

注意!这个问题对为什么两个具有相同哈希码的对象不一定相等

Note! This question is more interested in why two objects with the same hash code are not necessarily equals

推荐答案

这很简单.哈希码是整数,因此具有32位.现在以 Long 为例.由于它的长度为64位,因此其值比2 32 多得多.因此,必须有很多具有相同哈希码的值.

That's a simple matter of counting. A hash code is an integer so has 32 bits. Take now a Long for example. Since it is 64 bits long, there are much more values than 232. Hence there must be a lot of values having the same hash code.

这篇关于为什么具有相同哈希码的两个对象不一定相等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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