一般重写equals, 需要重写hashcode。for hash Collection usage
[quote]
public boolean equals(Object o){
if(o==this)
return true;
if(!(o instanceof CatchFinally))
return false;
CatchFinally cf = (CatchFinally)o;
return cf.keyfield == this.keyfield&&this.keyfield2.equals(cf.keyfield2);
}
public int hashCode(){
int result =17;
result = 37*result + keyfield;
result = 37*result + keyfield2;
return result;
}
[/quote]
[quote]
public boolean equals(Object o){
if(o==this)
return true;
if(!(o instanceof CatchFinally))
return false;
CatchFinally cf = (CatchFinally)o;
return cf.keyfield == this.keyfield&&this.keyfield2.equals(cf.keyfield2);
}
public int hashCode(){
int result =17;
result = 37*result + keyfield;
result = 37*result + keyfield2;
return result;
}
[/quote]
本文介绍了在Java中重写equals方法的同时需要重写hashCode方法的原因及实现方式。通过具体示例代码展示了如何根据对象的属性来正确实现这两个方法,确保了在使用基于哈希的集合类时对象行为的一致性。
341

被折叠的 条评论
为什么被折叠?



