在Java中覆盖equals和hashCode时应该考虑哪些问题? [英] What issues should be considered when overriding equals and hashCode in Java?
问题描述
覆盖等于
和 hashCode
时必须考虑哪些问题/陷阱?
理论(语言律师和数学倾向):
equals()
( javadoc )必须定义等价关系(它必须是自反,对称和传递 )。此外,它必须一致(如果未修改对象,则必须保持返回相同的值)。此外, o.equals(null)
必须始终返回false。
hashCode()
( javadoc )还必须一致(如果对象未按 equals()
进行修改,则必须保持返回相同的值这两种方法之间的关系是:
每当
a.equals(b)
,那么a.hashCode()
必须相同asb.hashCode()
。
在实践中:
如果你覆盖一个,那么你应该覆盖另一个。
使用与你相同的一组字段用于计算 equals()
来计算 hashCode()
。
使用优秀的助手类 EqualsBuilder 和 Apache Commons Lang 库的.htmlrel =noreferrer> HashCodeBuilder 。例如:
public class Person {
private String name;
private int age;
// ... ...
@Override
public int hashCode(){
return new HashCodeBuilder(17,31)。 //两个随机选择的素数
//如果派生:appendSuper(super.hashCode())。
追加(姓名)。
追加(年龄)。
toHashCode();
}
@Override
public boolean equals(Object obj){
if(!(obj instanceof Person))
return false;
if(obj == this)
返回true;
人rhs =(人)obj;
返回新的EqualsBuilder()。
//如果派生:appendSuper(super.equals(obj))。
append(name,rhs.name)。
追加(年龄,rhs.age)。
isEquals();
}
}
还要记住:
当使用基于散列的收藏或地图例如 HashSet ,< a href =http://download.oracle.com/javase/1.4.2/docs/api/java/util/LinkedHashSet.html\"rel =noreferrer> LinkedHashSet , HashMap , Hashtable 或 WeakHashMap ,确保你放入的关键对象的hashCode()当对象在集合中时,集合永远不会更改。确保这一点的防弹方法是使您的密钥不可变,还有其他好处。
What issues / pitfalls must be considered when overriding equals
and hashCode
?
The theory (for the language lawyers and the mathematically inclined):
equals()
(javadoc) must define an equivalence relation (it must be reflexive, symmetric, and transitive). In addition, it must be consistent (if the objects are not modified, then it must keep returning the same value). Furthermore, o.equals(null)
must always return false.
hashCode()
(javadoc) must also be consistent (if the object is not modified in terms of equals()
, it must keep returning the same value).
The relation between the two methods is:
Whenever
a.equals(b)
, thena.hashCode()
must be same asb.hashCode()
.
In practice:
If you override one, then you should override the other.
Use the same set of fields that you use to compute equals()
to compute hashCode()
.
Use the excellent helper classes EqualsBuilder and HashCodeBuilder from the Apache Commons Lang library. 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();
}
}
Also remember:
When using a hash-based Collection or Map such as HashSet, LinkedHashSet, HashMap, Hashtable, or WeakHashMap, make sure that the hashCode() of the key objects that you put into the collection never changes while the object is in the collection. The bulletproof way to ensure this is to make your keys immutable, which has also other benefits.
这篇关于在Java中覆盖equals和hashCode时应该考虑哪些问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!