Guergeiro / distributed-systems-2019

This repository contains our practical project for the class of distributed systems
https://cepos-e-mabecos.github.io/distributed-systems-2019/docs
MIT License
0 stars 2 forks source link

Definition of 'equals()' without corresponding definition of 'hashCode()'. #15

Closed Guergeiro closed 4 years ago

Guergeiro commented 4 years ago

The contract of equals() and hashCode() requires that equal objects have the same hashCode. Therefore, whenever you override equals() you must override hashCode() to ensure that your class can be used in hash-based collections.

Default configuration

<module name="EqualsHashCode"/>

Examples Example of incorrect code:

public class User {
    private String name;
    private int age;
    @Override
    public int hashCode() {
        int result = 17;
        result = 31 * result + name.hashCode();
        result = 31 * result + age;
        return result;
    }
}

Example of correct code:

public class User {
    private String name;
    private int age;
    @Override
    public int hashCode() {
        int result = 17;
        result = 31 * result + name.hashCode();
        result = 31 * result + age;
        return result;
    }

    @Override
    public boolean equals(Object o) {
        if (o == this) return true;
        if (!(o instanceof User)) {
            return false;
        }
        User user = (User) o;
        return user.name.equals(name) && user.age == age;
    }
}