代码
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
// if(!(obj instanceof Person)) 与上行的判断一样,利用instanceof关键字判断是否是Person的实例
return false;
Dog other = (Dog) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
注释
// 如果另一个对象和当前对象引用都一样,那么肯定是同一个对象实例,返回true
if (this == obj)
return true;
//如果另一个对象为null,返回false
if (obj == null)
return false;
//如果另一个对象和当前对象类型都不一样,那么肯定不相等,返回false
if (getClass() != obj.getClass())
return false;
//到这一步,传进来的对象肯定和当前对象类型一样了,那么直接转换下
Dog other = (Dog) obj;
//检查两个对象的age属性,不一样就返回false
if (age != other.age)
return false;
//检查name属性,由于name是字符串,不能直接用==比较。这里之所以没有直接name.equals(other.name)是因为如果name为null,会引起NullPointerException
if (name == null) {
//this.name为null而传进来的name却不为null,肯定不相等,返回false
if (other.name != null)
return false;
//this.name不为空,直接调用String的equals方法判断两个name是不是一样
} else if (!name.equals(other.name))
return false;
//如果前面的都满足,说明两个对象相等
return true;