自己重写equals()和hasCode()
package com.jerry.book;
public class Content
{
private int id;
private String name;
private String eEail;
private Address add;
public Content(int id,Address add){
this.id=id;
this.add=add;
}
public boolean equals(Object obj)
{
if(obj==null){
throw new NullPointerException();
}
if(this==obj){
return true;
}
if(!(obj instanceof Content)){
return false;
}
Content con=(Content)obj;
if(this.getAdd().equals(con.getAdd())&& // here
this.getId()==con.getId()){
return true;
}else {
return false;
}
}
@Override
public int hashCode()
{
if (result == 0)
{
result = 17;
result = 31 * result + id;
result = 31 * result + prefix;
result = 31 * result + lineNumber;
result = 31 * result + address;
hashCode = result;
}
return result;
}
public void setName(String name)
{
this.name = name;
}
public void setEEail(String eail)
{
eEail = eail;
}
public void setAdd(Address add)
{
this.add = add;
}
public String getName()
{
return name;
}
public String getEEail()
{
return eEail;
}
public Address getAdd()
{
return add;
}
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
}
、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、
public class Address
{
private String country;
private String province;
private String city;
private String town;
public Address(String country,String province, String city,String town){
this.country=country;
this.province=province;
this.city=city;
this.town=town;
}
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (!(obj instanceof Address))
{
return false;
}
Address add = (Address) obj;
if (this.getCity() == add.getCity() &&
this.getCountry() == add.getCountry() &&
this.getProvince() == add.getProvince() &&
this.getTown() == add.getTown())
{
return true;
} else
{
return false;
}
}
@Override
public int hashCode()
{
if (result == 0)
{
result = 17;
result = 31 * result + areaCode;
result = 31 * result + prefix;
result = 31 * result + lineNumber;
result = 31 * result + address;
hashCode = result;
}
return result;
}
public String getCountry()
{
return country;
}
public void setCountry(String country)
{
this.country = country;
}
public String getProvince()
{
return province;
}
public void setProvince(String province)
{
this.province = province;
}
public String getCity()
{
return city;
}
public void setCity(String city)
{
this.city = city;
}
public String getTown()
{
return town;
}
public void setTown(String town)
{
this.town = town;
}
}
、、、、、、、、、、、、、、单元测试类、、、、、、、、、、、、、、、、、、
import junit.framework.TestCase;
public class ContentTest extends TestCase
{
public void testaa()
{
Content con=new Content(1,new Address("aa","bb","cc","dd"));
Content con2=new Content(1,new Address("aa","bb","cc","dd"));
assertEquals(con, con2);
}
}