浏览 2575 次
锁定老帖子 主题:EqualsBuilder典型示例
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2008-07-08
1.判断是否为空(null),是则false 2.判断是否为同一类型(instanceof),否则false 3.判断是否为同一对象(==),是则true,否则执行EqualsBuilder package com.iwindyforest.eb; import org.apache.commons.lang.builder.EqualsBuilder; public class User { int id; String name; String sex; int age; String address; public User(int id, String name, String sex, int age, String address) { this.id = id; this.name = name; this.sex = sex; this.age = age; this.address = address; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public boolean equals(User user) { if(user == null) { return false; } if(!(user instanceof User)) { return false; } if(this == user) { return true; } else { return new EqualsBuilder() .append(this.getId(), user.getId()) .append(this.getAddress(), user.getAddress()) .append(this.getAge(), user.getAge()) .append(this.getName(), user.getName()) .append(this.getSex(), user.getSex)).isEquals(); } } } package com.iwindyforest.eb; public class EqualsBuilderTest { User a, b; public EqualsBuilderTest() { a = new User(1, "cyh", "male", 20, "shangdi haidian beijing"); b = new User(1, "cyh", "male", 20, "shangdi haidian beijing"); System.out.println(a.equals(null)); System.out.println(a.equals(new User(2, "cyh", "male", 20, "shangdi haidian beijing"))); System.out.println(a.equals(b)); } public static void main(String[] args) { new EqualsBuilderTest(); } } 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |