« | July 2025 | » | 日 | 一 | 二 | 三 | 四 | 五 | 六 | | | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | | | |
| 公告 |
关注电子政务、大型企业应用开发、Web、Workflow、MOM、MDA、RCP、GEF email:gmluyang@gmail.com
|
Blog信息 |
blog名称:SixSun的Blog 日志总数:152 评论数量:372 留言数量:13 访问次数:2372839 建立时间:2004年12月13日 |

| |
[J2SE / 基础类]Data Identity-equals与hashCode 随笔, 读书笔记
SixSun 发表于 2006/4/3 21:54:02 |
Mthod1:
public class Cat { ... public boolean equals(Object other) { if (this == other) return true; if (!(other instanceof Cat)) return false; final Cat cat = (Cat) other; if (!getName().equals(cat.getName())) return false; if (!getBirthday().equals(cat.getBirthday())) return false; return true; } public int hashCode() { int result; result = getName().hashCode(); result = 29 * result + getBirthday().hashCode(); return result; } }
Method2:
还可以使用org.apache.commons.lang.builder.EqualsBuilder与 org.apache.commons.lang.builder.HashCodeBuilder协助定义equals()与hashCode(),例如:
package onlyfun.caterpillar;import org.apache.commons.lang.builder.EqualsBuilder;import org.apache.commons.lang.builder.HashCodeBuilder;public class User { .... public boolean equals(Object obj) { if(obj == this) { return true; } if(!(obj instanceof User)) { return false; } User user = (User) obj; return new EqualsBuilder() .append(this.name, user.getName()) .append(this.phone, user.getPhone()) .isEquals(); } public int hashCode() { return new HashCodeBuilder() .append(this.name) .append(this.phone) .toHashCode(); }}
|
|
|