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

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

问题描述

我有一个带有 hashCode() 的向量类.它不是我写的,而是使用 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 个向量,开始"和结束"(代表一条线的端点).这两个向量的值是边界的特征.

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());
    }

在这里,我尝试为构成此边界的唯一向量二元组(开始和结束)创建一个好的 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,您应该会发现它可以为您生成 equalshashCode — 只需检查 Source 菜单.它会做同样的事情——枚举你的字段并创建一个 equals 方法来检查所有它们,然后选择 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天全站免登陆