equals方法重写要彻底
package day20;
public class Test05 {
public static void main(String[] args) {
// TODO Auto-generated method stub
/*
Address addr = new Address("北京","大兴区","11111");
//填家庭住址时先需要一个Address对象
User u = new User("zhangsan", addr);
*/
User u1 = new User("zhangsan", new Address("北京","大兴区","11111"));
User u2 = new User("zhangsan", new Address("北京","大兴区","11111"));
System.out.println(u1.equals(u2));
}
}
true
package day20;
public class User {
String name;
Address addr;
public User() {
}
public User(String name, Address addr)
{
this.name = name;
this.addr = addr;
}
//重写equals方法
//重写规则:当用户名和家庭住址都相同时,表示同一个用户
//这个equals判断的是User对象和User对象是否相等
public boolean equals(Object obj) {
if(obj == null || !(obj instanceof User)) {
return false;
}
if(this==obj) {
return true;
}
User u = (User)obj;
return this.name.equals(u.name) && this.addr.equals(u.addr);
}
}
package day20;
public class Address {
String city;
String street;
String zipcode;
public Address() {
}
public Address(String city, String street, String zipcode) {
this.city = city;
this.street = street;
this.zipcode = zipcode;
}
//注意:这里也要重写equals方法
//这个equals判断的是Address对象和Address对象是否相同
public boolean equals(Object obj) {
if(obj == null || !(obj instanceof Address)) {
return false;
}
if(this == obj) {
return true;
}
Address a = (Address)obj;
return this.city.equals(a.city) && this.street.equals(a.street) && this.zipcode.equals(a.zipcode);
}
}
ps:
1.在User的比较中,对于name是字符串类型的可以直接用equals方法比较(因为sun公司已经重写了比较字符串类型的equals方法)。而对于Address类型的比较还需要我们再重写equals方法比较Address类型
2.u2是user类型,但是u2作为参数传入,Object类型的能接收u2,u2向上转型为Object类型