Efficient hashCode() implementation

后端 未结 1 1436
盖世英雄少女心
盖世英雄少女心 2020-12-14 03:37

I often auto-generate an class\'s hashCode() method using IntelliJ IDEA and typically the method takes the form:

result = 31 * result + ...


        
相关标签:
1条回答
  • 2020-12-14 04:33

    Multiplying by 31 is fast because the JIT can convert it to a shift left by 5 bits and a subtract:

    x * 31 == (x << 5) - x
    

    Without any particular extra information, I'd stick to this approach. It's reasonably fast and likely to end up with reasonably well-distributed hash codes, and it's also easy to get right :)

    The size of the dataset doesn't really matter, but if you have particular extra information about the values you'll be work with (e.g. "it's always even") then you may be able to design a better hash function. I'd wait until it's an actual problem first though :)

    0 讨论(0)
提交回复
热议问题