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

后端 未结 6 1444
囚心锁ツ
囚心锁ツ 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:43

    Since Java 8 you can use

    Long.hashCode(guid);
    

    For older versions of Java you can use the following:

    Long.valueOf(guid).hashCode();
    

    Note that this solution creates a new Object for the stack, while the first doesn't (although it is likely that Java optimizes the object creation away..)

    Looking at the docs, both ways just use the following algorithm:

    (int)(this.longValue()^(this.longValue()>>>32))
    

    These are decent solutions since they make use of the Java library - always better to leverage off of something that has been tested already.

提交回复
热议问题