我有一个有4个属性的bean:
user
institutionId
groupId
postingDate
Run Code Online (Sandbox Code Playgroud)
我使用Eclipse生成equals和hashcode,但结果代码并不漂亮.是否有一种紧凑的方式来做同样的事情?假设我希望equals和hashcode使用所有属性或它们的子集.
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((groupId == null) ? 0 : groupId.hashCode());
result = prime * result + ((institutionId == null) ? 0 : institutionId.hashCode());
result = prime * result + ((postingDate == null) ? 0 : postingDate.hashCode());
result = prime * result + ((user == null) ? 0 : user.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ManGroupKey other = (ManGroupKey) obj;
if (groupId == null) {
if (other.groupId != null)
return false;
} else if (!groupId.equals(other.groupId))
return false;
if (institutionId == null) {
if (other.institutionId != null)
return false;
} else if (!institutionId.equals(other.institutionId))
return false;
if (postingDate == null) {
if (other.postingDate != null)
return false;
} else if (!postingDate.equals(other.postingDate))
return false;
if (user == null) {
if (other.user != null)
return false;
} else if (!user.equals(other.user))
return false;
return true;
}
Run Code Online (Sandbox Code Playgroud)
在Java 7中
public int hashCode() {
return Objects.hash(groupId, institutionId, postingDate, user);
}
Run Code Online (Sandbox Code Playgroud)
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
// cast to correct class
Target o = (Target)obj;
return Objects.equals(groupId, o.groupId) &&
Objects.equals(institutionId, o.institutionId) &&
Objects.equals(postingDate, o.postingDate) &&
Objects.equals(user, o.user);
}
Run Code Online (Sandbox Code Playgroud)
你可以压缩代码,但是你引入错误的几率远高于你做任何有用的东西.equals和hash code方法的所有部分都有一个原因.
如果它困扰你,大多数IDE都有折叠编辑器,只需点击黄色小框(通常),方法的所有内容都会被隐藏起来.
小智 4
您可以使用 Apache-common-langs( http://commons.apache.org/proper/commons-lang/ ) 类 HashCodeBuilder 和 EqualsBuilder 来执行此操作,而不是使用 eclipse 生成的代码:
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
public boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(this);
}
Run Code Online (Sandbox Code Playgroud)