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();
}
}