Java覆寫equeal和hashCode方法

使用Apache commons提供的commons-lang-xxx.jar包
下載地址:http://commons.apache.org/lang/

覆寫equals使用:org.apache.commons.lang.builder.EqualsBuilder
覆寫hashCode使用:org.apache.commons.lang.builder.HashCodeBuilder

來自apache官方的實例
public class Person {
String name;
int age;
boolean smoker;
...

// overwrite "equals"
public boolean equals(Object obj) {
if (obj == null) { return false; }
if (obj == this) { return true; }
if (obj.getClass() != getClass()) {
return false;
}
Person rhs = (Person) obj;
return new EqualsBuilder()
.appendSuper(super.equals(obj))
.append(field1, rhs.field1)
.append(field2, rhs.field2)
.append(field3, rhs.field3)
.isEquals();
}

// overwrite "hashCode"
public int hashCode() {
// you pick a hard-coded, randomly chosen, non-zero, odd number
// ideally different for each class
return new HashCodeBuilder(17, 37).
append(name).
append(age).
append(smoker).
toHashCode();
}

}
發佈了33 篇原創文章 · 獲贊 10 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章