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
© 2024 OneMinuteCode. All rights reserved.