将Java哈希码组合成“主”密码。哈希码 [英] Combining Java hashcodes into a "master" hashcode

查看:142
本文介绍了将Java哈希码组合成“主”密码。哈希码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实现了hashCode()的vector类。它不是由我编写的,而是使用2个素数来乘以2个向量分量,然后对它们进行异或运算。这是:

I have a vector class with hashCode() implemented. It wasn't written by me, but uses 2 prime numbers by which to multiply the 2 vector components before XORing them. Here it is:

    /*class Vector2f*/
...
    public int hashCode()
    {
        return 997 * ((int)x) ^ 991 * ((int)y); //large primes! 
    }

...因为这是来自已建立的Java库,我知道它工作得很好。

...As this is from an established Java library, I know that it works just fine.

然后我有一个Boundary类,它包含2个向量,start和end(表示一行的端点)。这两个向量的值是边界的特征。

Then I have a Boundary class, which holds 2 vectors, "start" and "end" (representing the endpoints of a line). The values of these 2 vectors are what characterize the boundary.

    /*class Boundary*/
...
    public int hashCode()
    {
        return 1013 * (start.hashCode()) ^ 1009 * (end.hashCode());
    }

这里我试图为独特的2创建一个好的hashCode()构成该边界的向量元组(开始和结束)。我的问题:这个hashCode()实现是否正常工作?

Here I have attempted to create a good hashCode() for the unique 2-tuple of vectors (start & end) constituting this boundary. My question: Is this hashCode() implementation going to work?

(注意我在后面的hashCode()实现中使用了2个不同的素数;我没有我知道这是否有必要,但是为了安全而不是在努力避免常见因素时更好,我猜 - 因为我认为这就是为什么素数很适合散列函数。)

(Note that I have used 2 different prime numbers in the latter hashCode() implementation; I don't know if this is necessary but better to be safe than sorry when trying to avoid common factors, I guess -- since I presume this is why primes are popular for hashing functions.)

推荐答案

这是正常做法。这看起来很合理。如果您正在使用Eclipse,您会发现它可以为您生成等于 hashCode - 只需检查来源菜单。它将执行相同的操作 - 枚举您的字段并创建一个等于方法来检查所有字段,然后选择 n 素数并执行您的操作已完成创建 hashCode 方法。

That's the normal practice. It looks pretty reasonable to me. If you're using Eclipse, you should find that it can generate equals and hashCode for you—just check the Source menu. It will do the same thing—enumerate your fields and create an equals method that checks all of them, then choose n prime numbers and do what you've done to create a hashCode method.

这篇关于将Java哈希码组合成“主”密码。哈希码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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