Overriding hashCode() - is this good enough?

前端 未结 2 1358
予麋鹿
予麋鹿 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:55

    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.

提交回复
热议问题