在项目中为了区分对象有时候需要覆盖equals方法,此时也需要覆盖hashCode方法;这里题外强调一下,如果hashCode相同,那么equals方法未必一定会返回true,但是equals如果返回true,那么hashCode一定相同。
package com.test;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
public class Policy
{
private String policyNo;
private String subType;
public Policy(String policyNo,String subType) {
this.policyNo = policyNo;
this.subType = subType;
}
public String getPolicyNo()
{
return policyNo;
}
public void setPolicyNo(String policyNo)
{
this.policyNo = policyNo;
}
public String getSubType()
{
return subType;
}
public void setSubType(String subType)
{
this.subType = subType;
}
@Override public boolean equals(Object obj)
{
if(!(obj instanceof Policy))
{
return false;
}
Policy castObj = (Policy)obj;
return new EqualsBuilder().append(getSubType(), castObj.getSubType()).append(getPolicyNo(), castObj.getPolicyNo()).isEquals();
}
@Override public int hashCode()
{
return new HashCodeBuilder().append(getSubType()).append(getPolicyNo()).toHashCode();
}
@Override public String toString()
{
return new ToStringBuilder(this).append(getSubType()).append(getPolicyNo()).toString();
}
}
Set s = new HashSet();
Policy p = new Policy("0","1");
Policy p2 = new Policy("0","1");
System.out.println(s.add(p) + p.toString());
System.out.println(s.add(p2) + p2.toString());
System.out.println(s.size());
truecom.test.Policy@1fb8ee3[1,0]
falsecom.test.Policy@10b30a7[1,0]
1
这里要用到commons-lang-2.0.jar
以下是自定义实现,但是不安全
@Override
public boolean equals(Object obj)
{
if(this == obj) {
return true;
}
if(obj instanceof Policy) {
Policy p = (Policy)obj;
if(p.getSubType().equals(subType) && p.getPolicyNo().equals(policyNo)) {
return true;
}
}
return false;
}
@Override
public int hashCode()
{
return policyNo.hashCode() + subType.hashCode();
}