equals标准写法

@Override
public boolean equals(Object obj) {
//为了提高效率
if(this == obj){
return true;
}

//为了提供程序的健壮性
//我先判断一下,obj是不是学生的一个对象,如果是,再做向下转型,如果不是,直接返回false。
//这个时候,我们要判断的是对象是否是某个类的对象?
//记住一个格式:对象名 instanceof 类名
//表示:判断该对象名是否是该类名一个对象
if(!(obj instanceof Student)){
return false;
}
//如果是就继续

Student s = (Student)obj;
//System.out.println("同一个对象,还需要向下转型并比较吗?");
return this.name.equals(s.name) && this.age == s.age;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) 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;
}

原文地址:https://www.cnblogs.com/wlmLinker/p/5737884.html