Boolean.hash code() [英] Boolean.hashCode()

查看:162
本文介绍了Boolean.hash code()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

散列code()班布尔的方法是这样实现的:

The hashCode() method of class Boolean is implemented like this:

public int hashCode() {
    return value ? 1231 : 1237;
}

为什么它使用1231和1237?为什么别的东西吗?

Why does it use 1231 and 1237? Why not something else?

推荐答案

1231和1237提供了两个(足够大)的任意素数即可。其他两个大质数会做的罚款。

1231 and 1237 are just two (sufficiently large) arbitrary prime numbers. Any other two large prime numbers would do fine.

为什么素数?

假设一秒钟,我们挑合数(非素数),说1000年和2000年当插入到布尔哈希表,的真正的和的的会进入斗 1000%N RESP 2000%N (其中 N 是桶的数量)。

Why primes?
Suppose for a second that we picked composite numbers (non-primes), say 1000 and 2000. When inserting booleans into a hash table, true and false would go into bucket 1000 % N resp 2000 % N (where N is the number of buckets).

现在注意到


  • 1000%8 同一个桶为 2000%8

  • 1000%10 同一个桶为 2000%10

  • 1000%20 同一个桶为 2000%20

  • ...

  • 1000 % 8 same bucket as 2000 % 8
  • 1000 % 10 same bucket as 2000 % 10
  • 1000 % 20 same bucket as 2000 % 20
  • ....

换句话说,这将导致的多次碰撞

in other words, it would lead to many collisions.

这是因为1000的分解(2 3 5 3 )和2000年的分解(2 4 5 3 )有那么多的共同因素。从而素数被选择,因为它们不太可能有与桶尺寸的任何常见的因素。

This is because the factorization of 1000 (23, 53) and the factorization of 2000 (24, 53) have so many common factors. Thus prime numbers are chosen, since they are unlikely to have any common factors with the bucket size.

为什么的的素数。会不会2,3办?

当计算哈希值codeS复合物很常见,添加哈希codeS的组件。如果太小的值在具有大量桶设置散列使用有一个与物体的不均匀分布结束了的危险。

Why large primes. Wouldn't 2 and 3 do?
When computing hash codes for composite objects it's common to add the hash codes for the components. If too small values are used in a hash set with a large number of buckets there's a risk of ending up with an uneven distribution of objects.

不要碰撞关系呢?布尔值只是有两个不同的值呢?

地图可以与其他对象包含布尔在一起。此外,作为由Drunix,指出了一个共同的方式来创建复合对象的散列函数是重用的子散code实现在这种情况下,这是很好的回报大素数。

Do collisions matter? Booleans just have two different values anyway?
Maps can contain booleans together with other objects. Also, as pointed out by Drunix, a common way to create hash functions of composite objects is to reuse the subcomponents hash code implementations in which case it's good to return large primes.

相关问题:

  • Why use a prime number in hashCode?
  • What is a sensible prime for hashcode calculation?
  • Why does Java's hashCode() in String use 31 as a multiplier?

这篇关于Boolean.hash code()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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