有效Java hashCode()实现中的位移 [英] Bit-shifting in Effective Java hashCode() implementation

查看:102
本文介绍了有效Java hashCode()实现中的位移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有人可以详细解释什么

I was wondering if someone could explain in detail what

(int)(l ^(l>>> 32) );

在以下哈希码实现中(由eclipse生成,但与Effective Java相同):

does in the following hashcode implementation (generated by eclipse, but the same as Effective Java):

private int i;
private char c; 
private boolean b;
private short s;
private long l;
private double d;
private float f;

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + i;
    result = prime * result + s;
    result = prime * result + (b ? 1231 : 1237);
    result = prime * result + c;
    long t = Double.doubleToLongBits(d);
    result = prime * result + (int) (t ^ (t >>> 32));
    result = prime * result + Float.floatToIntBits(f);
    result = prime * result + (int) (l ^ (l >>> 32));
    return result;
}

谢谢!

推荐答案

基本上它将底部32位的X的前32位进行异或。这是一个爆炸版本:

Basically it XORs the top 32 bits of a long with the bottom 32 bits. Here's an exploded version:

// Unsigned shift by 32 bits, so top 32 bits of topBits will be 0,
// bottom 32 bits of topBits will be the top 32 bits of l
long topBits = l >>> 32;

// XOR topBits with l; the top 32 bits will effectively be left
// alone, but that doesn't matter because of the next step. The
// bottom 32 bits will be the XOR of the top and bottom 32 bits of l
long xor = l ^ topBits;

// Convert the long to an int - this basically ditches the top 32 bits
int hash = (int) xor;

回答你的评论:你有一个很长的值,必须转换为int才能成为一部分哈希值(结果只有32位)。你打算怎么做?你可以只取底部的32位 - 但这意味着中的前32位的变化将被忽略,这不会使它成为一个非常好的散列。这样,输入总是的单个位的更改会导致哈希的单个位的更改。不可否认,你仍然可以轻松地获得冲突 - 例如,改变两个位7和39,或者将任何其他位置分开32个位置 - 但是,鉴于你来自2 64 可能值为2 32

To answer your comment: you have a long value which has to be converted into an int to be part of the hash (the result has to only be 32 bits). How are you going to do that? You could just take the bottom 32 bits - but then that means changes in only the top 32 bits would be ignored, which wouldn't make it a very good hash. This way, a change in a single bit of input always results in a change of a single bit of the hash. Admittedly you can still get collisions easily - change both bits 7 and 39, for example, or any other pair of bits 32 positions apart - but that's bound to be the case, given that you're going from 264 possible values to 232.

这篇关于有效Java hashCode()实现中的位移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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