How should I map long to int in hashCode()?

后端 未结 6 1452
囚心锁ツ
囚心锁ツ 2020-12-25 11:10

I have a range of objects that have a long field whose value uniquely identifies a particular object across my entire system, much like a GUID. I have overriden

6条回答
  •  忘掉有多难
    2020-12-25 11:40

    It's a bit of a minor thing if you're not using Guava already, but Guava can do this for you nicely:

    public int hashCode() {
      return Longs.hashCode(id);
    }
    

    That gives you the equivalent of Long.valueOf(id).hashCode():

    return (int) (value ^ (value >>> 32));
    

    Additionally, if you were to have other values or objects that were part of the hashcode, you could just write

    return Objects.hashCode(longValue, somethingElse, ...);
    

    The long would be autoboxed into a Long so you'd get the correct hashcode for it as part of the overall hashcode.

提交回复
热议问题