首页 > 编程语言 > 详细

重写java equals 方法的建议

时间:2016-10-30 16:23:06      阅读:189      评论:0      收藏:0      [点我收藏+]
@Override
public boolean equals(Object otherObject) {
//1.检测this 与 otherObject 是否引用同一个对象
if (this == otherObject) return true;
//2.检测otherObject 是否为null, 如果为null,返回false
if (null == otherObject) return false;
//3.比较this 与 ohterObject 是否属于同一个类
if(getClass() != otherObject.getClass()) return false;

if (!(otherObject instanceof Employee)) return false;

//4. 将otherObject 转换为相应的类类型变量
Employee employee = (Employee) otherObject;

//5.域比较
if (id != employee.id) return false;
if (Double.compare(employee.salary, salary) != 0) return false;
if (name != null ? !name.equals(employee.name) : employee.name != null) return false;

return true;
}

-- 摘《java核心技术:卷一》

重写java equals 方法的建议

原文:http://www.cnblogs.com/lyzblog/p/6013297.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!