Test of equality (equals and hash code method)

前端 未结 6 1499
挽巷
挽巷 2021-01-24 21:59

As per the below link

Hashcode and equals

So it is assumed that if 2 objects are equal (that is, equals() returns true), then their hashCodes() must retu

相关标签:
6条回答
  • 2021-01-24 22:26

    It is bad implementation of hashCode() , You should follow that contract.

    equals has nothing to do with hashcode independently.

    But when you use hashing data structure you should must follow this thing.

    0 讨论(0)
  • 2021-01-24 22:27

    First imp thing you should not use random number to implement the hashcode() method.

    @Override
    public int hashCode() {
        return name.hashcode();
    }
    @Override
    public boolean equals(Object o) {
        if(o !=null && o instanceOf Demo)
        {
            Demo d=(Demo) o;
            if(this.d.name==d.name)
            {
                return true;
            }
            else
            {
                false;
            }
            else
            {
                return false;
            }
        }
    
    0 讨论(0)
  • 2021-01-24 22:36

    In Hashcode it is always required that if two objects are equal then their hashCode always have to be the same other wise the hash collections(HashMap, HashSet etc. wont work correctly)

    Well in your case one of the implementations of can be -

    public int hashCode() {
        return this.getName();
    }
    

    OR if you want to mix it up a bit -

    public int hashCode() {
        return String.valueOf(this.getName()).hashCode();
    }
    
    0 讨论(0)
  • 2021-01-24 22:45

    You should never implement hashCode using random numbers! It should always be computed using the same fields as equals uses. Otherwise, your objects will be unusable as keys in HashMap, HashSet, etc.

    0 讨论(0)
  • 2021-01-24 22:47

    Some implementations (for instance HashMap) depend on the fact that when two instances are equal their hashcode should be the same. However, purely using equals will not check hashcodes for those instances.

    In the case of a hashmap, elemets are first divided into different hash buckets based on the hashcodes of objects (for performance reasons). Inside a bucket, equals is used to check object equality. If two equal instances don't have the same hashCode they will end up in different buckets and that might result in unexpected behaviour due to the contract violation.

    0 讨论(0)
  • 2021-01-24 22:49

    Actually the idea is that when you implemente the equals method you should implement the hashCode method, and if a.equals(b) then a.hashCode() == b.hashCode(). Although there isn't anything in the Java compiler or Runtime that enforces this.

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