What should be considered when overriding equals() and hashCode() in Java?

Asked 1 years ago, Updated 1 years ago, 72 views

What should be considered when overriding equals() and hashCode()?

java hashcode override equals

2022-09-22 21:41

1 Answers

eauqls() (javadoc) defines an equivalence relationship. And the result should always be the same. (Even if the data on the object is modified, it should always be able to return the same value.) In addition, o.equals(null) should always return false.

hashCode() (javadoc) must also be consistent at all times. (hashCode() should always return the same value if the object is not modified in terms of equals().)

The relationship between the two methods must always satisfy the following conditions:

When a.equals(b), a.hashCode() and b.hashCode() must be the same.

If you want to override either one, you must override both.

Use the same set of fields for calculating equals() and hashCode().

From the Apache Commons Lang library, EqualsBuilder and HashCodeBuilder. Here's an example.

public class Person {
    private String name;
    private int age;
    // ...

    @Override
    public int hashCode() {
        return new HashCodeBuilder(17, 31). // // two randomly chosen prime numbers
            // // if deriving: appendSuper(super.hashCode()).
            append(name).
            append(age).
            toHashCode();
    }

    @Override
    public boolean equals(Object obj) {
       if (!(obj instanceof Person))
            return false;
        if (obj == this)
            return true;

        Person rhs = (Person) obj;
        return new EqualsBuilder().
            // // if deriving: appendSuper(super.equals(obj)).
            append(name, rhs.name).
            append(age, rhs.age).
            isEquals();
    }
}

HashSet, LinkedHashSet, HashMap, hashtable or href="https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html" target=""" target="_blank">collection or When using https://docs.oracle.com/javase/8/docs/api/java/util/Map.html" target="_blank">map, never change the hashCode() of the key object that you insert into the collection when the object exists in the collection. The best way to guarantee this is to make a key that doesn't change. This also provides an additional benefit of .


2022-09-22 21:41

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.