equals是超父类Object的方法,即所有的java对象都拥有此方法.
下面是Object的源码
public boolean equals(Object obj) {
return (this == obj);
}
可以看出,Bean如果不重写equals方法,直接调用则是==比较
==比较,基本类型通常是比较的值,引用类型比较的是引用即引用地址值.
String类型和基本类型的包装类,equals方法还是比较的值,因为这些类重写了equals方法.
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
上面是String重写的equals,可以看出字符串比较时会先比较引用地址,如果地址不同,然后会比较字符串长度,然后比较每一个字符,如果相同则结果依然true.
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}
public boolean equals(Object obj) {
if (obj instanceof Long) {
return value == ((Long)obj).longValue();
}
return false;
}
基本类型的包装类,会直接转为基本类型使用==比较,即基本类型比较值.
所以当我们需要判断使用的POJO唯一时,就必须要重写equals方法,IDE重写的equals方法模板,会对每一个属性进行比较,如果属性有引用类型,也必须保证该引用类型重写了equals,比如下面的pojo
@Setter
@Getter
@ToString
public class PersonRequest {
/**
* 联系人基本信息
*/
@Valid()
private PersonBasicInfoAO personBasicInfo;
/**
* 联系人任职信息
*/
@Valid
private List<PersonDutyAO> personDuties;
/**
* 人员联系方式入参
*/
@Valid
private List<PersonContactAO> personContacts;
/**
* 教育信息
*/
@Valid
private List<PersonEducationAO> personEducations;
/**
* 工作经历
*/
@Valid
private List<PersonResumeAO> personResumes;
/**
* 请求来源(PC端/移动端)
*/
private String requestSource;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof PersonRequest)) return false;
PersonRequest that = (PersonRequest) o;
if (personBasicInfo != null ? !personBasicInfo.equals(that.personBasicInfo) : that.personBasicInfo != null)
return false;
if (personDuties != null ? !personDuties.equals(that.personDuties) : that.personDuties != null) return false;
if (personContacts != null ? !personContacts.equals(that.personContacts) : that.personContacts != null)
return false;
if (personEducations != null ? !personEducations.equals(that.personEducations) : that.personEducations != null)
return false;
if (personResumes != null ? !personResumes.equals(that.personResumes) : that.personResumes != null)
return false;
return requestSource != null ? requestSource.equals(that.requestSource) : that.requestSource == null;
}
}
网友评论