一组三个字段的哈希码 [英] Hash Code for a group of three fields

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

问题描述

我有三个字段,即

  1. Number1
  2. Number2
  3. 时间

我正在尝试用Java语言编写一个函数,该函数为上述字段返回唯一的哈希值( long必须是哈希的返回类型).然后,此哈希将用于在HashSet中存储与上述字段相对应的数据库行.我刚开始编写哈希码功能,有人可以复习一下我拥有的内容吗.

I am trying to write a function in java that returns a unique hash value (long needs to be the return type of hash) for the above fields. This hash would then be used to store database rows corresponding to the above mentioned fields in a HashSet. I am new to writing a hash code function, can someone please review what I have.

public class HashCode {

    private long Number1;
    private long Number2;
    String Time;

    public HashCode(long Number1, long Number2, String Time){
        this.Number1 = Number1;
        this.Number2 = Number2;
        this.Time = Time;
    }

    public long getHashCode() {
        long hash = 3;
        hash = 47 * hash + (long) (this.Number1 ^ (this.Number1 >>> 32));
        hash = 47 * hash + (long) (this.Number2 ^ (this.Number2 >>> 32));
        hash = 47 * hash + (this.Time != null ? this.Time.hashCode() : 0);
        return hash;
    }
}

推荐答案

我认为这是hashCode的特殊版本.否则,您将需要覆盖hashCode,而不定义新方法.像HashSet这样的容器不会获得您自己的哈希码.

I take it's a special version of hashCode. Otherwise you would need to overwrite hashCode, don't define a new method. Containers like HashSet don't get your own hash code.

  • 因此对于long的专用版本,您不需要使用xor(^),因为它已经很长了.只需使用long值即可.
  • 在使用String的hashCode时,它使用的时间不会太长,仅用于int,因此不会使用"您的所有空间.您可以根据需要复制String的hashCodelong.
  • 其他看起来不错.
  • So for your specialized version for long, you do not need to use the xor (^) because it's already long. Just use the long value.
  • When using hashCode of String it's not for long, just for int, so it will not "use" all your space. You could duplicate the hashCode of String with longs for your purpose.
  • else looks good.

(顺便说一下,成员应使用小写字母,Time也应是私有的.)

(By the way, members should be called with lower letters and Time should be private as well.)

这篇关于一组三个字段的哈希码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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