Overriding hashCode() - is this good enough?

前端 未结 2 1324
予麋鹿
予麋鹿 2021-01-12 14:14

For a class whose fields are solely primitive, ex.:

class Foo
{
    int a;
    String b;
    boolean c;
    long d;

    boolean equals(Object o)
    {
              


        
相关标签:
2条回答
  • 2021-01-12 14:49

    It totally depends on what your data will look like. Under most circumstances, this would be a good approach. If you'll often have b end with a number, then you'll get some duplicate codes for unequal objects, as JacobM's answer shows. If you know ahead of time that b will pretty much never have a number value at the end, then this is a reasonable hashing algorithm.

    0 讨论(0)
  • Your hash code does satisfy the property that if two objects are equal, then their hash codes need to be equal. So, in that way it is 'good enough'. However, it is fairly simple to create collisions in the hash codes which will degrade the performance of hash based data structures.

    I would implement it slightly differently though:

    public int hashCode() {
        return a * 13 + b.hashCode() * 23 + (c? 31: 7);
    }
    

    You should check out the documentation for the hashCode() method of Object. It lays out the things that the hash code must satisfy.

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